Swift - Optionals
Aus Wikizone
Links[Bearbeiten]
Swift (Programmiersprache)
Optionals[Bearbeiten]
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
Optional Anwendungsfälle[Bearbeiten]
// 5 WAYS TO WORK WITH OPTIONALS
let myOptional: String?
myOptional = "Stephan"
// 1. FORCE UNWRAP
let text:String = myOptional!
/**
The least safe way - will crash on runtime if myOptional is nil
so it totally depends on the user to make sure myOptional is valid.
*/
// 2. Check for nil value
if myOptional != nil{
print(myOptional!)
}else{
print("myOptional was found to be nil")
}
/**
More safe but not comfortable
*/
// 3. OPTIONAL BINDING
if let safeOptional = myOptional {
print(safeOptional)
}else{
print("myOptional was found to be nil")
}
/**
Create a safe version of a optional which we can use safely
*/
// 4. NIL COALESCING OPERATOR
let string: String = myOptional ?? "This is a default value"
/**
gives us the possibility to provide an alternative value which is used if Optional as nil
*/
// 5. OPTIONAL CHAINING
struct MyStruct {
var myProperty = 123
func myMethod(){
print("I'm a method")
}
}
let myStruct: MyStruct? // optional caus not initialized yet
myStruct = MyStruct() // now it is initialised
print(myStruct?.myProperty ?? "myStuct is nil - cannot access myProperty")
/**
Used for optional structs or classes I
optional?.property
optional?.method
ONLY IF OPTIONAL IS INITIALISED method will execute or property will accessed
the compiler checks if myStruct has a value and only if it has than it will go to the chained method
*/