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!
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With