Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set optionals that are nil to an empty string? [duplicate]

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!
    }
like image 361
Declan McKenna Avatar asked Dec 04 '22 00:12

Declan McKenna


1 Answers

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.

like image 52
Dalija Prasnikar Avatar answered Dec 10 '22 11:12

Dalija Prasnikar