简体   繁体   English

如果值为 nil,则 Swift 改为设置默认值

[英]Swift if value is nil set default value instead

I have this code part:我有这个代码部分:

let strValue = String()
textfield.stringValue = strValue!

The problem is that strValue can be nil.问题是strValue可以为零。

For this I check it like this:为此,我像这样检查它:

if strValues.isEmpty() {
   textfield.stringValue = ""
} else {
   textfield.stringValue = strValue!
}

But I there an quicker and easier way to do this?但是我有更快更简单的方法来做到这一点吗?

I read something like ??我读过类似的东西?? to solve it.来解决它。 But I don't know how to use it?但是不知道怎么用?

UPDATE thanks a lot for the many feedbacks.更新非常感谢许多反馈。 now i unterstand the ??现在我不明白了?? operator, but how i realize it in this situation?操作员,但在这种情况下我如何实现呢?

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))

how can i usee the ??我怎么能用?? operator in the last line of my code?操作符在我代码的最后一行?

UPDATE 2 Okay i got it!更新 2好的,我明白了!

txtStreet.stringValue = (((adresse?.value(at: 0) as? NSMutableDictionary)?.value(forKey: kABAddressStreetKey) as? String)) ?? ""

you can do like this but your strValue should be optional type你可以这样做,但你的 strValue 应该是可选类型

let strValue:String?
textfield.stringValue = strValue ?? "your default value here"

The ?? ?? is the nil-coalescing operator, and took me a bit to understand, too.是 nil-coalescing 运算符,我也花了一点时间来理解。 It is a useful tool for simplifying code though.不过,它是简化代码的有用工具。 A simple explanation of it is "unless that's nil, then this" so a ?? b对它的一个简单解释是“除非那是零,那么这个”所以a ?? b a ?? b returns a if it has a value and b if it doesn't. a ?? b如果有值则返回a如果没有则返回b You can chain them together and return the first non-nil value.您可以将它们链接在一起并返回第一个非 nil 值。 Example, a ?? b ?? c ?? d ?? e例如, a ?? b ?? c ?? d ?? e a ?? b ?? c ?? d ?? e a ?? b ?? c ?? d ?? e returns the first non-nil value, or e if they are all nil before it. a ?? b ?? c ?? d ?? e返回第一个非 nil 值,或者e如果它们在它之前都是 nil。

Nil-Coalescing Operator 零合并算子

You can create an optional string extension.您可以创建可选的字符串扩展。 I did the following to set an optional string to empty if it was nil and it works :我做了以下操作,将一个可选字符串设置为空,如果它是 nil 并且它可以工作:

extension Optional where Wrapped == String {

    mutating func setToEmptyIfNil() {
        guard self != nil else {
            self = ""
            return
        }
    }

}

Using nil-coaleasing operator , we can avoid code to unwrap and clean our code.使用nil-coaleasing operator ,我们可以避免代码解包和清理我们的代码。

To provide simple default value when an optional is nil :当可选项为 nil 时提供简单的默认值:

let name : String? = "My name"
let namevalue = name ?? "No name"
print(namevalue)

Important thing to note here is that you don't need to unwrap it using if let or guard here and it will be implicitly unwrapped but safely .这里要注意的重要一点是,您不需要在这里使用if letguard解包它,它将被隐式解包但安全

Also it is useful to make your code much cleaner and short :使您的代码更加简洁和简短也很有用:

   do {
        let text = try String(contentsOf: fileURL, encoding: .utf8)
    }
    catch {print("error")}

Above code can be written as :上面的代码可以写成:

let text = (try? String(contentsOf: fileURL, encoding: .utf8)) ?? "Error reading file"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM