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

标签 swift swift2 option-type

<分区>

现在我使用上面的代码将可选值设置为空字符串(如果它为 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.

关于swift - 如何将 nil 的可选值设置为空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38787377/

相关文章:

ios - swift : UICollectionView invalidateLayout not getting triggered

ios - 在 iOS 应用程序上发送 MIDI 信息时出现问题

ios - 评论主 Storyboard上的 View

ios - Researchkit:如何从 UIWebView 手动切换到下一步

java-8 - 如何将 java.util.Optional<Something> 映射到某物?在 Kotlin

swift - 具有选项的良好编程风格

haskell - 折叠一个可折叠的 Maybe (Monoid),忽略 Haskell 中的缺失值

swift - 我无法在 Swift 3 的 navigationController 中执行我的 segue

ios - UIWindow 上的偏移导致标签栏在向后滑动时显示两次

ios - 转换为 swift 3.0 时,UIButton 上 'dismiss()' 的使用不明确