数组是:var closestAnnotations:[MKAnnotation]
我想知道为什么swift编译器不会接受:
let closestStationAnnotations = closestAnnotations.filter({
$0.dynamicType === StationAnnotation.self
})
Cannot convert value of type (_) -> Bool to expected argument type (MKAnnotation) -> Bool
但接受:
let closestStationAnnotations = closestAnnotations.filter({
(annotation : MKAnnotation) -> Bool in
annotation.dynamicType === StationAnnotation.self
})
答案 0 :(得分:1)
我一直在尝试不同版本的代码(使用Xcode 7)。修复很明显,使用
let closestStationAnnotations = closestAnnotations.filter({
$0 is StationAnnotation
})
这是测试类型的正确方法,没有任何问题。
我注意到有一些简单的代码会让错误消失
let closestStationAnnotations = closestAnnotations.filter({
print("\($0)")
return ($0.dynamicType === StationAnnotation.self)
})
但是,这不起作用:
let closestStationAnnotations = closestAnnotations.filter({
return ($0.dynamicType === StationAnnotation.self)
})
如果您注意到错误消息,编译器会将闭包视为(_) -> Bool
。
这使我得出结论,表达式$0.dynamicType
以某种方式被优化出来。
最有趣的是
let closestStationAnnotations = closestAnnotations.filter({
return true
})
会触发相同的错误。
所以我认为有两个编译器错误:
编译器无法根据数组的类型推断出参数,并且错误是因为(_) -> Bool
在(Type) -> Bool
上调用时应被视为[Type]
。< / p>
编译器以某种方式优化$0.dynamicType
,这显然是错误的。