swift 使用Init方法而不传递参数?

mwkjh3gx  于 11个月前  发布在  Swift
关注(0)|答案(1)|浏览(106)

我有一个CLPlacemark的数组。我在下面的例子,我不明白为什么第二个代码是正确的。
示例1:此代码正确。

let placemarks: [CLPlacemark]
....

placemarks
.compactMap({ placemark in
      Location(placemark: placemark)
})

...

字符串
示例2:此代码也是正确的。

let placemarks: [CLPlacemark]
....

placemarks
.compactMap(Location.init(placemark:))

...


你知道为什么我可以创建位置而不传递参数吗?

e0bqpujr

e0bqpujr1#

初始化器可以被认为是一个常规函数,它返回初始化器初始化的任何类型的值。当你显式写出init时,它们就有了一个类型。
就像你可以写:

func makeLocation(placemark: CLPlacemark) -> Location? { ... }
// I'm not *calling* `makeLocation` here - I'm just assigning the function itself to f
let f: (CLPlacemark) -> Location? = makeLocation(placemark:) // or just makeLocation

字符串
你也可以这样写:

struct Location {
    init?(placemark: CLPlacemark) { ... }
}
let f: (CLPlacemark) -> Location? = Location.init(placemark:) // or just Location.init


如果这是你第一次看到函数本身被用作 * 值 *,而不是被调用,请参见Swift指南的这一节。
它在compactMap中以同样的方式工作。compactMap需要一个(T) -> U?类型的函数,其中TU是类型参数。
你可以传递lambda { placemark in Location(placemark: placemark) }。这个lambda的类型是(CLPlacemark) -> Location?。但是Location.init的类型也是(CLPlacemark) -> Location?匹配这个模式,所以你也可以将它传递给compactMap

相关问题