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