felix
felix

Reputation: 31

swift optional unexpected error

I'm new here. I'm puzzled with an error. This swift code causes an error that I cannot understand. It merely comes from the Apple documentation "Optional Chaining as an Alternative to Forced Unwrapping"

class Person {
    var residence: Residence?
}
class Residence {
    var numberOfRooms = 1
}

let john = Person()
john.residence = Residence()
john.residence.numberOfRooms = 5   

// error here : 'Residence?' does not have a member named 'numberOfRooms'

Upvotes: 0

Views: 153

Answers (1)

Antonio
Antonio

Reputation: 72750

The residence property of Person is an optional, so in order to access to its content you have to unwrap it. You can use optional chaining to do that:

john.residence?.numberOfRooms = 5
              ^

That means: if residence is not nil, continue evaluating what's at the right side of the expression, otherwise cancel.

The error seems a nonsense, because Residence does have a property named numberOfRooms. The point is that john.residence is an optional type, and optionals are instances of an enum, Optional<T> - which doesn't have a numberOfRooms property. Using optional chaining the Residence instance is unwrapped from the enum (i.e. the optional), and so the error disappears because Residence has that property.

More info at Optional Chaining (note this is the documentation mentioned in the question)

Upvotes: 4

Related Questions