Understanding Optional Chaining in Swift Programming
Learn about optional chaining in Swift programming with examples involving students, dormitories, and room numbers. Explore how to handle optionals to avoid crashes and safely access nested properties.
Download Presentation
Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
E N D
Presentation Transcript
14.1 (?) nil
// optional chaining class Student { var dorm: Dormitory? } class Dormitory { var numberOfRooms = 2 } let peter = Student() let rooms = peter.dorm?.numberOfRooms print("Dormitory has \(rooms) rooms")
14.2 class Student { var dorm: Dormitory? } init(numberOfRooms: Int) { self.numberOfRooms = numberOfRooms } var location: Location? } class Dormitory { var numberOfRooms: Int class Location { var dormitoryName: String? var street: String? } func printNumberOfRooms() { print("The number of rooms is \(numberOfRooms)") }
class Student { var dorm: Dormitory? } class Location { var dormitoryName: String? var street: String? } class Dormitory { var numberOfRooms: Int let peter = Student() if let roomNumber = peter.dorm?.numberOfRooms { print("Peter's dormitory has \(roomNumber) rooms") } else { print("Unabel to retrieve the number of rooms") } func printNumberOfRooms() { print("The number of rooms is \(numberOfRooms)") } init(numberOfRooms: Int) { self.numberOfRooms = numberOfRooms } var location: Location? }
14.2.2 printNumberOfRooms
class Student { var dorm: Dormitory? } class Location { var dormitoryName: String? var street: String? } class Dormitory { var numberOfRooms: Int // call method let peter = Student() peter.dorm = Dormitory(numberOfRooms: 10) peter.dorm!.printNumberOfRooms() func printNumberOfRooms() { print("The number of rooms is \(numberOfRooms)") } init(numberOfRooms: Int) { self.numberOfRooms = numberOfRooms } var location: Location? }
14.3 Location peterLocation Location peterLocation peter.dorm?.location
class Student { var dorm: Dormitory? } class Location { var dormitoryName: String? var street: String? } class Dormitory { var numberOfRooms: Int func printNumberOfRooms() { print("The number of rooms is \(numberOfRooms)") } init(numberOfRooms: Int) { self.numberOfRooms = numberOfRooms } var location: Location? } // multiple chain let peter = Student() peter.dorm = Dormitory(numberOfRooms: 10) let peterLocation = Location() peterLocation.dormitoryName = "BigHouse Building" peterLocation.street = "Hsingchang 777" peter.dorm?.location = peterLocation print(peter.dorm?.location?.dormitoryName) print(peter.dorm?.location?.street)