Deco Deco - 1 year ago 61
Swift Question

How to set optionals that are nil to an empty string?

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!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download