Chapter #3, Challenge number 1

let firstName = "Ted"
var lastName: String

if firstName == “Ted” {
lastName = “Healy”
} else if firstName == “Moe” {
lastName = “Howard”
}

let fullName = firstName + " " + lastName

+++++++++++++++++++++++++++++++++++
I wonder why the code above is having error "variable ‘lastName’ used before being initialized"
and it will worked when I initialise
var lastName: String = “”

isn’t that variable lastName filled with value inside if else statement and by the time it called to assign fullName constant it already have value? why I should fill empty string “” to make this worked?

lastName only gets a value if the first name is “Ted” or “Moe”. Swift isn’t going to look harder at the code and say oh, hey, the first name is always “Ted” so never mind.

if you added

} else {
lastName = “Nobody”
}

so that lastName always got assigned something, then it wouldn’t complain.

This topic was automatically closed after 166 days. New replies are no longer allowed.