【问题标题】:Swift return type clarificationSwift 返回类型说明
【发布时间】:2018-02-08 11:49:46
【问题描述】:

我看到一个 Swift 函数写成如下:

func calculation(imageRef: CGImage) -> (red: [UInt], green: [UInt], blue: [UInt]) {

 ...
 ...
}

我需要知道上面函数的返回类型是什么。我无法将它与任何已知类型联系起来,如果有的话,它在 Objective-C 中的等价物是什么?将这个函数翻译成 Objective-C 的方法是什么?

【问题讨论】:

  • 返回类型 (=tuple) 在 ObjC 中无法表示;在 ObjC 中你可以做(​​但不限于)一些丑陋的事情,例如,-(void)caluclationWithImageRef:(CGImage)imageRef red:(NSArray<NSNumber *> **)red green:(NSArray<NSNumber *> **)green blue:(NSArray<NSNumber *> **)blue { ... }

标签: ios objective-c swift swift4


【解决方案1】:

这个函数返回的是一个元组

元组可以在一个对象中保存各种类型,但与数组不同的是,您不能在其中添加或删除对象。

From Apple Developer Swift Guides:

元组将多个值组合成一个复合值。元组中的值可以是任何类型,并且彼此不必是相同的类型。

Objective-C 中不存在元组。 You can find more information about that here.

【讨论】:

    【解决方案2】:

    这叫Tuple learn here

    它允许在单个变量下分组多个值。

    Objective c 不支持 tuple 。在 objc 中你必须使用 dictionary 并且你必须使用键 redgreen 和 'blue 以数组作为值

    【讨论】:

      【解决方案3】:
      func calculation(imageRef: CGImage) -> (red: [UInt], green: [UInt], blue: [UInt]) {
      
       ...
       ...
      }
      

      上面的方法返回 tuple(一组不同的值,你可以在 Swift 中使用)。

      您也可以返回不带命名参数元组

      func calculation(imageRef: CGImage) -> ([UInt], [UInt],[UInt]) {
      
       ...
       ...
      }
      

      您可以像这样访问返回值(对于未命名的元组参数):

      let returnedTuple = calculation(imagRef)
      print(returnedTuple.0) //Red
      print(returnedTuple.1) //Green
      print(returnedTuple.2) //Blue
      

      (对于命名元组参数):

      let returnedTuple = calculation(imagRef)
      print(returnedTuple.red) //Red
      print(returnedTuple.green) //Green
      print(returnedTuple.blue) //Blue
      

      Objective-C 中没有元组的等价性。

      【讨论】:

        【解决方案4】:

        这个方法返回一个元组

        func calculation(imageRef: CGImage) -> (red: [UInt], green: [UInt], blue: [UInt]) {
        
        
            return ([],[],[])
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-12-21
          • 2017-08-24
          • 1970-01-01
          • 2013-04-30
          • 2012-07-14
          • 1970-01-01
          相关资源
          最近更新 更多