Last active
April 24, 2023 15:58
-
-
Save MoussaHellal/cf2483eb10e0da58b84c3d424ffcc602 to your computer and use it in GitHub Desktop.
Optional Chaining example in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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