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

Declan McKenna

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!
    }
Dalija Prasnikar

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Set nil string pointer to empty string

Swift optionals nil check

Do Optionals default to nil?

Swift: Testing optionals for nil

In Swift, how do I avoid both optionals and nil object references?

How to check Multiple string is not nil and not empty in swift 5?

Decoding empty string into nil with Codable

regex with all components optionals, how to avoid empty matches

How to set the field separator to an empty string?

AngularJs, how to set empty string in URL

How to set label to empty string in dropdown?

redis. how set key name with empty string (not empty value)

Assigning nil to generic optionals in Swift

Swift nil Optional String = Empty String

optionals with get and set

Decoding empty JSON string value into nil with Decodable

Testing for empty or nil-value string

Shorter Alternative to ternary to generate empty string if nil?

Checking for nil parameter and if that parameter is an empty string in Swift

Swift optional assignment, deal with nil/empty string

Swift 4 Change nil jsonElement to an empty string

Rails 5 tries to save the empty string as nil

How can I create an inline dictionary in Swift while omitting potentially nil optionals as values?

How do I create a function that returns the first non-nil, non-empty string passed to it?

How to test if a parameter has been set to the empty string?

How to set that a column can't be empty string? Laravel

How to set empty string as password for MYSQL database in properties file.

How to set the initial value of ng-model to an empty string in angularjs?

How do I set a database column to the empty string in a Rails fixture?