OP 提交的错误报告:
已解决(2017 年 1 月 3 日提交给 master 的修复),因此在即将推出的 Swift 3.1 中应该不再是问题。
这似乎是与以下情况相关的错误(Swift 2.2 中不存在,仅 3.0 中):
- 对表达式中的至少 3 个项使用强制展开运算符 (
!
)(使用至少 2 个基本运算符进行测试,例如+
或-
)。
- 出于某种原因,鉴于上述情况,Swift 搞砸了表达式的类型推断(特别是对于
x!
术语本身,在表达式中)。
对于以下所有示例,让:
let a: String? = "a"
let b: String? = "b"
let c: String? = "c"
存在的错误:
// example 1
a! + b! + c!
/* error: ambiguous reference to member '+' */
// example 2
var d: String = a! + b! + c!
/* error: ambiguous reference to member '+' */
// example 3
var d: String? = a! + b! + c!
/* error: cannot convert value of type 'String'
to specified type 'String?' */
// example 4
var d: String?
d = a! + b! + c!
/* error: cannot assign value of type 'String'
to specified type 'String?' */
// example 5 (not just for type String and '+' operator)
let a: Int? = 1
let b: Int? = 2
let c: Int? = 3
var d: Int? = a! + b! + c!
/* error: cannot convert value of type 'Int'
to specified type 'Int?' */
var e: Int? = a! - b! - c! // same error
错误不存在:
/* example 1 */
var d: String? = a! + b!
/* example 2 */
let aa = a!
let bb = b!
let cc = c!
var d: String? = aa + bb + cc
var e: String = aa + bb + cc
/* example 3 */
var d: String? = String(a!) + String(b!) + String(c!)
但是,由于这是 Swift 3.0- dev,我不确定这是否真的是一个“错误”,以及在尚未生产的代码版本中报告“错误”的政策是什么,但可能你应该提交雷达为此,以防万一。
至于回答你的问题是如何规避这个问题:
- 使用例如中间变量,如Bug 不存在:上面的示例 2,
- 或者明确告诉 Swift 3-term 表达式中的所有术语都是字符串,如Bug not present: Example 3 above,
或者,更好的是,使用可选绑定的安全展开,例如使用可选绑定:
var d: String? = nil
if let a = a, b = b, c = c {
d = a + b + c
} /* if any of a, b or c are 'nil', d will remain as 'nil';
otherwise, the concenation of their unwrapped values */