class ElectionPoll {
var candidate: Pollbooth?
}
class Pollbooth {
var name = "MP"
}
let cand = ElectionPoll()
if let candname = cand.candidate?.name {
print("Candidate name is \(candname)")
} else {
print("Candidate name cannot be retreived")
}
In the above code I thought the output would be Candidate name is MP but the output is Candidate name cannot be retreived. Can anyone explain this?
CodePudding user response:
var candidate: Pollbooth?
This creates a candidate variable with type of Pollbooth
.
let cand = ElectionPoll()
In this line just creates ElectionPoll
object. When you try to execute this cand.candidate?.name
the cand.candidate
variable is nil because you cannot set any value.
If you try to get the value directly then you can try this way
let cand = ElectionPoll()
cand.candidate = Pollbooth()
Or
class ElectionPoll {
var candidate = Pollbooth()
}
Hope this will help you.
CodePudding user response:
The problem has little to do with optional chaining, you just didn't set any value to candidate
.
What you do is creating an ElectionPoll
variable:
let cand = ElectionPoll()
The candidate
property of ElectionPoll
is Optional
and thus implicitly has a nil
default value. Classes in Swift only have inherited and an empty initializers. So unless you add an init(candidate: Pollbooth?)
, the only way to provide candidate
with a value is through the property:
cand.candidate = Pollbooth()
And after that candidate
finally has its non-nil
value.