<分区>
现在我使用上面的代码将可选值设置为空字符串(如果它为 nil),如果它有值则将其解包。这只有三行代码,但这对我来说是一个非常常见的操作,所以我想知道是否有更优雅的方法来做到这一点?
var notesUnwrapped:String = ""
if(calendarEvent.notes != nil){
notesUnwrapped = calendarEvent.notes!
}
<分区>
现在我使用上面的代码将可选值设置为空字符串(如果它为 nil),如果它有值则将其解包。这只有三行代码,但这对我来说是一个非常常见的操作,所以我想知道是否有更优雅的方法来做到这一点?
var notesUnwrapped:String = ""
if(calendarEvent.notes != nil){
notesUnwrapped = calendarEvent.notes!
}
最佳答案
您可以使用 nil 合并运算符 ??
var notesUnwrapped: String = calendarEvent.notes ?? ""
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 - Researchkit:如何从 UIWebView 手动切换到下一步
java-8 - 如何将 java.util.Optional<Something> 映射到某物?在 Kotlin
haskell - 折叠一个可折叠的 Maybe (Monoid),忽略 Haskell 中的缺失值
swift - 我无法在 Swift 3 的 navigationController 中执行我的 segue