Can someone help me understand why I am unable to set the the middleName parameter to a value? I have declared it as an optional, but whenever I try to initialize it, I always get nil running through the guard statement in the getFullName() function.
var firstName: String
var middleName: String?
var lastName: String
init(firstName: String, middleName: String, lastName: String)
{
self.firstName = firstName
self.middleName? = middleName
self.lastName = lastName
}
func getFullName() -> String
{
guard let midName = self.middleName else
{
return "\(firstName) \(lastName)"
}
return "\(firstName) \(midName) \(lastName)"
}
let person = Person(firstName: "Foo", middleName: "Bar", lastName: "FooBar")
The returned value when printed is "Foo Foobar". Why is that?
You don't need (or want) to unwrap the property when you are assigning to it. You just refer to it directly;
init(firstName: String, middleName: String, lastName: String)
{
self.firstName = firstName
self.middleName = middleName
self.lastName = lastName
}
When middleName is nil (as it is initially) the conditional unwrap self.middleName? fails, so the assignment isn't performed.
Conditionally unwrapping self.middleName is effectively a shorthand way of saying
if self.middleName != nil {
self.middleName = middleName
}
Since middleName is optional, then you may want to make the initialisation parameter optional too:
init(firstName: String, middleName: String?=nil, lastName: String)
{
self.firstName = firstName
self.middleName = middleName
self.lastName = lastName
}
If a property is optional you have to make the corresponding parameter in the init method optional, too, otherwise it's pointless to declare the property as optional.
init(firstName: String, middleName: String?, lastName: String)
{
self.firstName = firstName
self.middleName = middleName
self.lastName = lastName
}
You can even assign nil as default value to be able to omit the parameter
init(firstName: String, middleName: String? = nil, lastName: String)
{
self.firstName = firstName
self.middleName = middleName
self.lastName = lastName
}
let person = Person(firstName: "Foo", lastName: "FooBar")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With