0

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 propertyvar 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 ?

2
  • Go back to "The Basics" and read about Optional values. Commented Nov 26, 2015 at 7:43
  • Not clear that you said. Would you please explain it? Commented Nov 26, 2015 at 8:03

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your nice answer. But my question is not optional related. I just want to know, how second article access class property without declaring object?
This is not the class property, it create object with default value of nil because it optional property

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.