为什么Swift编译器不能推断出这个闭包的类型?
所以我编写代码来区分我的应用程序的多个版本:
static var jsonURLNL = { if ProcessInfo.processInfo.environment["CONSUMER"] != nil { return URL(string: "consumerURL")! } return URL(string: "professionalURL")! }() 但是我遇到了编译器错误:
为什么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的引用:
和SR-1570 bug report. (链接和引用均从How flatMap API contract transforms Optional input to Non Optional result?复制). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |