nil coalescing operator,nilcoalescing

來源:互聯網
上載者:User

nil coalescing operator,nilcoalescing

nil coalescing operator ?? 就是 optional和 三元運算子?:的簡寫形式。


例如一個optional String類型的變數


var a:String?// println(a != nil ? a! : "shabi")println(a ?? "shabi")    // shabi// a ?? "shabi" equals a != nil ? a! : "shabi"a = "hecheng"println(a ?? "shabi")  // hecheng


// 這個運算子添加於2014-08-04 (The Swift Programming Language Revision History)


AFNetWorking的創始人 Mattt Thompson在他的個人部落格裡就曾用過這個運算子:

http://nshipster.com/swift-literal-convertible/

struct Set<T: Hashable> {    typealias Index = T    private var dictionary: [T: Bool]    init() {        self.dictionary = [T: Bool]()    }    var count: Int {        return self.dictionary.count    }    var isEmpty: Bool {        return self.dictionary.isEmpty    }    func contains(element: T) -> Bool {        return self.dictionary[element] ?? false // 這裡    }    mutating func put(element: T) {        self.dictionary[element] = true    }    mutating func remove(element: T) -> Bool {        if self.contains(element) {            self.dictionary.removeValueForKey(element)            return true        } else {            return false        }    }}

因為字典通過['key']擷取後是一個Optional類型,如果這個key對應的value不存在的話,可以通過??運算子設定一個不存在時的預設值(false)。




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.