Usare gli Optionals in Swift

Mattepuffo's logo
Usare gli Optionals in Swift

Usare gli Optionals in Swift

Dalla versione 4 anche Swift è dotata degli Optionals.

Sostanzialmente sono dei tipi di dato che possono essere null.

Vediamo un esempio:

var str: String?
str = "CIAO!"

if str != nil {
    print(str)
} else {
    print("NULLA")
}

Il compilatore ci avvertirà che la variabile verrà convertita in Any: e questo è quello che vedremo in console:

Optional("CIAO!")

Dobbiamo fare una conversione, e possiamo farla in due modi:

var str: String?
str = "CIAO!"

if str != nil {
    print(str!)
} else {
    print("NULLA")
}

Oppure:

var str: String!
str = "CIAO!"

if str != nil {
    print(str)
} else {
    print("NULLA")
}

Enjoy!


Condividi

Commentami!