微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift – 如何设置空字符串为零的选项?

参见英文答案 > When should I compare an optional value to nil?                                    5个
现在我使用上面的代码将可选项设置为空字符串(如果它是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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐