unwrapping optional
In Swift, optionals are used to represent values that might be nil. Before using the value, you must unwrap the optional safely to avoid runtime crashes. For example
if let fixtureDetail = viewModel.fixtureFullDetail {
ScoreView(fixtureDetails: fixtureDetail)
}
optional binding
using if let
var name: String? = "Hai"
if let unwrappedName = name {
print("Hello, \(unwrappedName)")
} else {
print("Name is nil")
}
using guard let (typically used in functions)
func greet(_ name: String?) {
guard let unwrappedName = name else {
print("No name provided")
return
}
print("Hello, \(unwrappedName)")
}
forced unwrapping
let name: String? = "Hai"
print(name!) // Prints "Hai", crashes if `name` is nil
nil coalescing operator (??)
this is similar to the elvis operator ?? in kotlin val name = optionalName ?: "Default"
let name: String? = nil
let finalName = name ?? "Anonymous"
print(finalName) // Prints "Anonymous"
optional chaining
let text: String? = "hello"
let upper = text?.uppercased() // returns Optional("HELLO")
implicit unwrapped optionals (string!)
this is similar to lateinit var
in kotlin
var name: String! = "Hai"
print(name) // Treated like a normal String after unwrapping