Questo codice funziona nel parco giochi:
var x: Int? = nil
let y = 5
x = x ?? y // x becomes 5
e
var x: Int? = 6
let y = 5
x = x ?? y // x stays 6
Tra l'altro qui ci sono alcune varianti di verifica di zero:
if x != nil {
// classic
}
if x != .None {
// nil in Swift is enum with value .None
}
if let _x = x {
// if you need it's value
}
if let _ = x {
// if you don't need it's value
}
UPD: Codice per progetto - copia ed eseguilo:
var x: Int? = nil
let y = 5
x = x ?? y
print (x)
x = 7
x = x ?? y
print (x)
L'operatore ?? = è stato rifiutato da Swift evolution: http://article.gmane.org/gmane.comp.lang.swift.evolution/7694 – yzyzsun