加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:51:54 所属栏目:百科 来源:网络整理
导读:参见英文答案 When should I compare an optional value to nil?????????????????????????????????????5个 现在我使用上面的代码将可选项设置为空字符串(如果它是nil)并且如果它具有值则将其解包.这只是三行代码,但对我来说这是一个非常常见的操作,所以我想
参见英文答案 > 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读