我正在尝试快速连接多个字符串3:
var a:String? = "a" var b:String? = "b" var c:String? = "c" var d:String? = a! + b! + c!
编译时出现以下错误:
error: cannot convert value of type 'String' to specified type 'String?' var d:String? = a! + b! + c! ~~~~~~~~^~~~
以前它可以迅速运行2。我不确定为什么它不再起作用了。
OP提交的错误报告:
该问题已解决(修复将于2017年1月3日提交给母版),因此在即将到来的Swift 3.1中不再是问题。
这似乎是与以下情况相关的错误(在Swift 2.2中仅存在于3.0中):
!
+
-
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 ,因此我不确定这是否确实是“错误”,以及不确定在尚未生产的代码版本中报告“错误”的政策是什么,但是您可能应该提起诉讼为此,以防万一。
至于如何规避此问题,请回答以下问题:
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 */