Swift - Optionals

Aus Wikizone
Version vom 28. Dezember 2022, 21:40 Uhr von 134.3.86.14 (Diskussion) (Die Seite wurde neu angelegt: „Optionals are a way to prevent code from running in a null exeption. ? declares a optional ! forces a optional to unwrap to original type (with the danger to…“)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Wechseln zu: Navigation, Suche

Optionals are a way to prevent code from running in a null exeption.

? declares a optional ! forces a optional to unwrap to original type (with the danger to create an error) ?? is used to give a alternative return if the optional contains nil

/**
 Optionals can provide a kind of safety check if variables not set
 */
//var playerName: String = nil // not working - needs to be a String
var playerName: String? = nil // ? declares Optional so the value can be nil or a string

playerName = "jacktheripper" // try commenting out

print(playerName!) // ! is the counterpart of ? it forces to unwrap to a string - error when playerName not set so it's not good style
if playerName != nil {print(playerName)}else{print("no name given")}
print(playerName ?? "no name given") // shorthand for the line above