4

Right now I use the above code to set an optional to an empty string if it's nil and to unwrap it if it has a value. This is only three lines of code but this is a very common operation for me so I'm wondering if there's a more elegant way to do this?

var notesUnwrapped:String = ""
    if(calendarEvent.notes != nil){
        notesUnwrapped = calendarEvent.notes!
    }
Declan McKenna
  • 4,321
  • 6
  • 54
  • 72
  • 2
    Use `if let`. Explained here: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID330 – Eric Aya Aug 05 '16 at 10:49
  • 1
    You should really read the language guide. – Alexander Aug 05 '16 at 14:05

1 Answers1

16

You can use nil coalescing operator ??

var notesUnwrapped: String = calendarEvent.notes ?? ""

Swift Operators

The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

Dalija Prasnikar
  • 27,212
  • 44
  • 82
  • 159