简体   繁体   中英

access a class type variable from another class in swift

I am trying to learn swift and i am reading this article https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html . In VideoMode class an object like resolution of type Resolution is created as a property of VideoMode class's . After that an object let someVideoMode = VideoMode() of VideoMode class's is created and access width property of Resolution struct by someVideoMode.resolution.width . This concept is clear to me. But i am facing problem when i am reading this article https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html#//apple_ref/doc/uid/TP40014097-CH21-ID245

In this article Person class just create a property var residence: Residence? of Residence class's. Not create an object. After that, create a object john of Person class's and accessing property of Residence class's. What is happening here? Please tell me, how Person class access property of Residence class ?

In second case we have optional property and by default it initialize to nil . If we look at what the optional type is, we will see that this is enum like:

enum Optional<T> {
    case Some(T)
    case None
}

And it can be Some Type like Int for example or Residence or None and in this case it's have nil value. And by default in your example it's None and in this code from documentation:

 if let roomCount = john.residence?.numberOfRooms { print("John's residence has \\(roomCount) room(s).") } else { print("Unable to retrieve the number of rooms.") } 

it will print

"Unable to retrieve the number of rooms."

But if you init residence like this:

let john = Person()

// Init residence
john.residence = Residence()

if let roomCount = john.residence?.numberOfRooms {
    print("John's residence has \(roomCount) room(s).")
} else {
    print("Unable to retrieve the number of rooms.")
}

it will print:

"John's residence has 1 room(s)."

because the optional type enum will return Some(Residence) and you will have access to it value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM