9

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)) ?? ""
Trombone0904
  • 4,132
  • 8
  • 51
  • 104
  • 1
    Do you mean `nil` or an empty string `""`? – Sweeper Jul 01 '17 at 17:01
  • The nil coalescing operator does the job concisely: `textField.stringValue = strValue ?? ""` – Rob Jul 01 '17 at 17:05
  • 1
    Probably a duplicate of [Providing a default value for an Optional in Swift?](https://stackoverflow.com/q/24099985/2976878), but your question makes no sense because `strValue` is not optional. – Hamish Jul 01 '17 at 17:06
  • Your *code part* does not compile because `strValue` is clearly non-optional. – vadian Jul 01 '17 at 17:06

4 Answers4

26

you can do like this but your strValue should be optional type

let strValue:String?
textfield.stringValue = strValue ?? "your default value here"
Irshad Ahmad
  • 1,363
  • 11
  • 17
3

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"
Abhijith
  • 3,094
  • 1
  • 33
  • 36
2

The ?? is the nil-coalescing operator, and took me a bit to understand, too. It is a useful tool for simplifying code though. A simple explanation of it is "unless that's nil, then this" so a ?? b returns a if it has a value and b if it doesn't. You can chain them together and return the first non-nil value. Example, a ?? b ?? c ?? d ?? e returns the first non-nil value, or e if they are all nil before it.

Nil-Coalescing Operator

1

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

}
Anil Arigela
  • 436
  • 2
  • 8