Skip to content

Instantly share code, notes, and snippets.

@MoussaHellal
Last active April 24, 2023 15:58
Show Gist options
  • Save MoussaHellal/cf2483eb10e0da58b84c3d424ffcc602 to your computer and use it in GitHub Desktop.
Save MoussaHellal/cf2483eb10e0da58b84c3d424ffcc602 to your computer and use it in GitHub Desktop.
Optional Chaining example in Swift
struct Person {
var name: String
var information: Information?
}
struct Information {
var id: String
var age: Int
}
var person = Person(name: "Moussa", information: Information(id: "id-1231424", age: 28))
// Using optional chaining to safely access the age property of the person's infrormation
if let age = person.information?.age {
print("The person's age is \(age)")
} else {
print("No age found")
}
// Changing the person's information to nil to see how optional chaining handles it
person.information = nil
// Using optional chaining to safely access the age property of the person's information, which is now nil
if let age = person.information?.age {
print("The person's age is \(age)")
} else {
print("No age found")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment