Nil coalescing Operator

Source: Internet
Author: User

Nil coalescing operator ?? Is the optional and ternary operators? .


For example, an optional string type variable


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


// This operator is added on (the swift programming language revision history)


Mattt Thompson, founder of afnetworking, used this operator in his blog:

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 // here} 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 }}}

Because the dictionary obtained through ['key'] is an optional type. If the value corresponding to this key does not exist, you can use ?? Set the default value (false) when the operator does not exist ).

Nil coalescing Operator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.