swift编译器为何有时不接受速记参数名称? [英] Why doesn't the swift compiler sometimes accept the shorthand argument name?

查看:81
本文介绍了swift编译器为何有时不接受速记参数名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该数组是:var closestAnnotations:[MKAnnotation]

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

I was wondering why the swift compiler won't accept :

    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
    })

推荐答案

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

I have been trying out different versions of your code (using Xcode 7). The fix is obvious, using

let closestStationAnnotations = closestAnnotations.filter({
    $0 is StationAnnotation
})

这是测试类型的正确方法,可以正常工作.

which is the correct way to test types, works without any problems.

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

I have noticed that there is simple code that makes the error go away

let closestStationAnnotations = closestAnnotations.filter({
    print("\($0)")
    return ($0.dynamicType === StationAnnotation.self)
})

但是,这不起作用:

let closestStationAnnotations = closestAnnotations.filter({
    return ($0.dynamicType === StationAnnotation.self)
})

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

If you notice the error message, the compiler sees the closure as (_) -> Bool.

这使我得出结论,表达式$0.dynamicType在某种程度上已优化.

That leads me to the conclusion that the expression $0.dynamicType is somehow optimized out.

最有趣的

let closestStationAnnotations = closestAnnotations.filter({
    return true
})

将触发相同的错误.

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

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

  1. The compiler cannot infer the argument from the type of the array and that's wrong because (_) -> Bool should be considered as (Type) -> Bool when called on [Type].

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

The compiler somehow optimizes $0.dynamicType out and that's obviously wrong.

这篇关于swift编译器为何有时不接受速记参数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆