为什么swift编译器有时不接受速记参数名称?

Mat*_*ler 5 swift swift2

该数组是: var closestAnnotations:[MKAnnotation]

我想知道swift编译器为什么不接受:

    let closestStationAnnotations = closestAnnotations.filter({
        $0.dynamicType === StationAnnotation.self
    })
Run Code Online (Sandbox Code Playgroud)

Cannot convert value of type (_) -> Bool to expected argument type (MKAnnotation) -> Bool

但接受:

    let closestStationAnnotations = closestAnnotations.filter({
        (annotation : MKAnnotation) -> Bool in
        annotation.dynamicType === StationAnnotation.self
    })
Run Code Online (Sandbox Code Playgroud)

Sul*_*han 1

我一直在尝试您的代码的不同版本(使用 Xcode 7)。修复方法很明显,使用

let closestStationAnnotations = closestAnnotations.filter({
    $0 is StationAnnotation
})
Run Code Online (Sandbox Code Playgroud)

这是测试类型的正确方法,没有任何问题。

我注意到有一个简单的代码可以使错误消失

let closestStationAnnotations = closestAnnotations.filter({
    print("\($0)")
    return ($0.dynamicType === StationAnnotation.self)
})
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用:

let closestStationAnnotations = closestAnnotations.filter({
    return ($0.dynamicType === StationAnnotation.self)
})
Run Code Online (Sandbox Code Playgroud)

如果您注意到错误消息,编译器会将闭包视为(_) -> Bool.

这让我得出这样的结论:该表达式$0.dynamicType在某种程度上被优化了。

最有趣的是

let closestStationAnnotations = closestAnnotations.filter({
    return true
})
Run Code Online (Sandbox Code Playgroud)

会触发同样的错误。

所以我认为有两个编译器错误:

  1. 编译器无法从数组的类型推断参数,这是错误的,因为(_) -> Bool应该被视为(Type) -> Bool在调用时[Type]

  2. 编译器以某种方式$0.dynamicType进行了优化,这显然是错误的。

  • @MatthieuRiegler 实际上,我更惊讶的是编译器不会将“return true”推断为有效的闭包。 (2认同)