【发布时间】:2017-12-05 09:58:26
【问题描述】:
我有这个代码部分:
let strValue = String()
textfield.stringValue = strValue!
问题是strValue可以为nil。
为此,我这样检查:
if strValues.isEmpty() {
textfield.stringValue = ""
} else {
textfield.stringValue = strValue!
}
但是我有更快更简单的方法吗?
我读了?? 之类的东西来解决它。但是不知道怎么用?
更新 非常感谢您的许多反馈。 现在我明白了??操作员,但是在这种情况下我是如何实现的呢?
let person = PeoplePicker.selectedRecords as! [ABPerson]
let address = person[0].value(forProperty: kABAddressProperty) as?
ABMultiValue
txtStreet.stringValue = (((address?.value(at: 0) as! NSMutableDictionary).value(forKey: kABAddressStreetKey) as! String))
我怎样才能使用?我的代码最后一行中的运算符?
更新 2 好的,我明白了!
txtStreet.stringValue = (((adresse?.value(at: 0) as? NSMutableDictionary)?.value(forKey: kABAddressStreetKey) as? String)) ?? ""
【问题讨论】:
-
你的意思是
nil还是空字符串""? -
nil 合并运算符简洁地完成了这项工作:
textField.stringValue = strValue ?? "" -
可能是Providing a default value for an Optional in Swift? 的副本,但您的问题没有意义,因为
strValue不是可选的。 -
您的 代码部分 无法编译,因为
strValue显然是非可选的。
标签: swift