Skip to content

Instantly share code, notes, and snippets.

@deathlezz
Last active October 16, 2021 08:40
Show Gist options
  • Save deathlezz/91f9623a87ac5e4efa42947f57caf106 to your computer and use it in GitHub Desktop.
Save deathlezz/91f9623a87ac5e4efa42947f57caf106 to your computer and use it in GitHub Desktop.
Simple use of optionals in Swift 5.
//
// Simple use of optionals
//
// unwrapping with if let
var nickname: String? = nil
if let unwrap = nickname {
print("Successfully created user as: \(unwrap).")
} else {
print("User creation failed.")
}
// unwrapping with guard let
func brand(name: String?) {
guard let unwrapped = name else {
print("There is no name!")
return
}
print("My favourite brand is \(unwrapped).")
}
brand(name: nil) // There is no name!
// nil coalescing
func queue(position: Int) -> String? {
if position == 1 {
return "You are next."
} else {
return nil
}
}
let person = queue(position: 5) ?? "You must wait."
print(person) // You must wait.
// failable initializer
struct User {
var password: String
init?(password: String) {
if password.count >= 8 {
self.password = password
} else {
return nil
}
}
}
let jack = User(password: "passwrd")
print(jack?.password ?? "Password too short!") // Password too short!
// typecasting
class Engine { }
class Electric: Engine { }
class Petrol: Engine {
func makeBrap() {
print("Brap!")
}
}
let engines = [Electric(), Petrol(), Electric(), Petrol()]
for engine in engines {
if let brapMaker = engine as? Petrol {
brapMaker.makeBrap()
}
}
// Brap!
// Brap!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment