如何将 nil 的可选值设置为空字符串?

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

现在我使用上面的代码将可选值设置为空字符串(如果它为 nil),如果它有值则将其解包。这只有三行代码,但这对我来说是一个很常见的操作,所以我想知道是否有更优雅的方法来做到这一点?

var notesUnwrapped:String = ""
    if(calendarEvent.notes != nil){
        notesUnwrapped = calendarEvent.notes!
    }

您可以使用 nil 合并运算符 ??

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.