Reputation: 2786
I'm watching all the swift tutorials from Apple, but I'm having problems with one of the examples:
class Person {
var residence: Residence?
}
class Residence {
var address: Address?
}
class Address {
var buildingNumber: String? = "234"
var streetName: String? = "Main St."
var appartmentNumber: String?
}
let paul = Person()
var addressNumber: Int?
addressNumber = paul.residence?.address?.buildingNumber?.toInt()
if let number = addressNumber {
"correct"
} else {
"fault"
}
It's always printing out "fault". Is there something painfully obvious I'm missing?
Upvotes: 0
Views: 203
Reputation: 15566
Well you are never actually creating a valid Residence
or Address
, if you change your code to:
class Person {
// actually create a residence object
var residence: Residence? = Residence()
}
class Residence {
// actually create a address object
var address: Address? = Address()
}
class Address {
// ...
}
let paul = Person()
var addressNumber: Int?
// Before Paul was never assigned a valid residence, now one will be created
addressNumber = paul.residence?.address?.buildingNumber?.toInt()
if let number = addressNumber {
"correct"
} else {
"fault"
}
// gives you `correct`
then it should work great!
Upvotes: 2
Reputation: 32054
Think it through, one step at a time. Particularly, your optional chaining:
addressNumber = paul.residence?.address?.buildingNumber?.toInt()
Ask yourself:
What is paul
?
What is paul
's residence
property set to?
What is the address
of paul
's residence
?
Hint: You shouldn't make it past step 2.
Upvotes: 2
Reputation: 6831
let paul = Person()
You do nothing else to paul
including setting his optional residence variable. So in the next line of code, you are accessing paul
's residence which is nil
.
addressNumber = paul.residence?.address?.buildingNumber?.toInt()
^ failing right here, residence? returns nil
So with optional chaining, this entire expression returns nil
, so when compared in your next if let
statement, it is false. This is why the else
clause is being executed.
Upvotes: 2
Reputation: 21845
You never initialize anything except Person()
, so the residence
property on paul
is nil
.
So, in the following optional chain:
addressNumber = paul.residence?.address?.buildingNumber?.toInt()
^ you get nil here and don't continue
This means that addressNumber
is nil
.
Upvotes: 1