微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么Swift编译器不能推断出这个闭包的类型?

所以我编写代码来区分我的应用程序的多个版本:

static var jsonURLNL =  {
    if ProcessInfo.processInfo.environment["CONSUMER"] != nil {
        return URL(string: "consumerURL")!
    }
    return URL(string: "professionalURL")!
}()

但是我遇到了编译器错误

Unable to infer complex closure return type; add explicit type to disambiguate

为什么Swift编译器不知道这会返回一个URL?我认为在这种情况下这是相当明显的.

我对这个问题的目标不是对Xcode或Swift进行批评,而是增加我对编译器如何在Swift中推断类型的了解.

解决方法

闭包的返回类型只有在自动推断时才会自动推断
闭包由一个表达式组成,例如:

static var jsonURLNL =  { return URL(string: "professionalURL")! }()

或者如果可以从调用上下文推断出类型:

static var jsonURLNL: URL =  {
    if ProcessInfo.processInfo.environment["CONSUMER"] != nil {
        return URL(string: "consumerURL")!
    }
    return URL(string: "professionalURL")!
}()

要么

static var jsonURLNL = {
    if ProcessInfo.processInfo.environment["CONSUMER"] != nil {
        return URL(string: "consumerURL")!
    }
    return URL(string: "professionalURL")!
}() as URL

简化示例:此单表达式闭包编译:

let cl1 = { return 42 }

但是这个多表达式闭包不会:

let cl2 = { print("Hello"); return 42 }
// error: unable to infer complex closure return type; add explicit type to disambiguate

以下行编译,因为类型是从上下文推断出来的:

let cl3 = { print("Hello"); return 42 } as () -> Int

let y1: Int = { print("Hello"); return 42 }()

let y2 = { print("Hello"); return 42 }() as Int

另见Jordan Rose in this mailing list discussion的引用:

Swift’s type inference is currently statement-oriented,so there’s no easy way to do [multiple-statement closure] inference. This is at least partly a compilation-time concern: Swift’s type system allows many more possible conversions than,say,Haskell or OCaml,so solving the types for an entire multi-statement function is not a trivial problem,possibly not a tractable problem.

SR-1570 bug report.

(链接和引用均从How flatMap API contract transforms Optional input to Non Optional result?复制).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐