我有一个CLPlacemark的数组。我在下面的例子,我不明白为什么第二个代码是正确的。
示例1:此代码正确。
let placemarks: [CLPlacemark]
....
placemarks
.compactMap({ placemark in
Location(placemark: placemark)
})
...
字符串
示例2:此代码也是正确的。
let placemarks: [CLPlacemark]
....
placemarks
.compactMap(Location.init(placemark:))
...
型
你知道为什么我可以创建位置而不传递参数吗?
1条答案
按热度按时间e0bqpujr1#
初始化器可以被认为是一个常规函数,它返回初始化器初始化的任何类型的值。当你显式写出
init
时,它们就有了一个类型。就像你可以写:
字符串
你也可以这样写:
型
如果这是你第一次看到函数本身被用作 * 值 *,而不是被调用,请参见Swift指南的这一节。
它在
compactMap
中以同样的方式工作。compactMap
需要一个(T) -> U?
类型的函数,其中T
和U
是类型参数。你可以传递lambda
{ placemark in Location(placemark: placemark) }
。这个lambda的类型是(CLPlacemark) -> Location?
。但是Location.init
的类型也是(CLPlacemark) -> Location?
匹配这个模式,所以你也可以将它传递给compactMap
。