Swift if value is nil set default value instead

Viewed 19753

I have this code part:

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

The problem is that strValue can be nil.

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!

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

Using nil-coaleasing operator, we can avoid code to unwrap and clean our code.

To provide simple default value when an optional is 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.

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"

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 :

extension Optional where Wrapped == String {

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

}
Related