初始化器可以被认为是一个常规函数,它返回初始化器正在初始化的任何类型的值.当您显式写出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
如果这是您第一次看到函数本身被用作value,而不是被调用,请参见this section of the Swift Guide.
在compactMap
年里,它也是这样运作的.compactMap
需要类型(T) -> U?
的函数,其中T
和U
是类型参数.
你可以通过拉姆达{ placemark in Location(placemark: placemark) }
米.这辆兰布达应该是(CLPlacemark) -> Location?
型的.但Location.init
的类型也是(CLPlacemark) -> Location?
与此模式匹配,所以您也可以将其传递给compactMap
.