我有這樣的代碼部分:斯威夫特如果值是零設定的默認值,而不是
let strValue = String()
textfield.stringValue = strValue!
的問題是,strValue
可以是零。
爲此,我檢查一下這樣的:
if strValues.isEmpty() {
textfield.stringValue = ""
} else {
textfield.stringValue = strValue!
}
但我有一個更快,更簡單的方法來做到這一點?
我讀了類似??
來解決它。但我不知道如何使用它?
UPDATE 非常感謝許多反饋意見。 現在我unterstand ?? ??操作員,但在這種情況下我是如何意識到的?
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))
我該怎麼用?運算符在我的代碼的最後一行?
UPDATE 2 好吧,我明白了!
txtStreet.stringValue = (((adresse?.value(at: 0) as? NSMutableDictionary)?.value(forKey: kABAddressStreetKey) as? String)) ?? ""
你的意思是'nil'或一個空字符串'「」'? – Sweeper
nil合併運算符簡潔地完成工作:'textField.stringValue = strValue ?? 「''' – Rob
可能是[在Swift中提供可選的默認值?](https://stackoverflow.com/q/24099985/2976878)的副本,但是你的問題沒有意義,因爲'strValue'不是可選的。 – Hamish