为什么在Swift 3中使用字符串插值时,隐式解包的选项不会被解包?
示例:在操场中运行以下代码
var str: String!
str = "Hello"
print("The following should not be printed as an optional: \(str)")
Run Code Online (Sandbox Code Playgroud)
产生这个输出:
The following should not be printed as an optional: Optional("Hello")
Run Code Online (Sandbox Code Playgroud)
当然我可以用+运算符连接字符串,但我在我的应用程序中几乎无处不在使用字符串插值,现在因为这个而无法工作(bug?).
这甚至是一个bug还是他们故意用Swift 3改变这种行为?
如果我在我的类中声明了一个隐式解包的可选项,然后我在Dictionary类型中引用[String : Any]它,它就不会被解包.为什么是这样?为什么Any,这不是可选的,不强迫它打开?
var aString: String! = "hello"
var params : [String : Any] = [
"myString" : aString
]
print(params)
// This prints ["myString": Swift.ImplicitlyUnwrappedOptional<Swift.String>.some("hello")]
Run Code Online (Sandbox Code Playgroud)
请注意,如果我将字典指定为类型[String : String],它将被解包,但这对于我需要多个类型时没有用Dictionary.