使用 swift 4.2 时遇到奇怪的问题并使用 ??
解包
简单代码:
var someVar:String?
override func viewDidLoad() {
someOp = "print some string"
subTitleLabel.text = "text one" + someVar ?? "unwrapped"
}
编译器抛出错误:
Value of optional type 'String?' must be unwrapped to a value of type 'String'
Swift 4.2 有什么变化?
最佳答案
这是因为 operator precedence .
+
的优先级高于??
所以要加括号
subTitleLabel.text = "text one" + (someVar ?? "unwrapped")
关于ios - Swift 4.2 解包问题 (??),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53084001/