Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Init with Optional Parameters - not possible?

Tags:

swift

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?

like image 500
decipher Avatar asked Jan 24 '26 10:01

decipher


2 Answers

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
}
like image 55
Paulw11 Avatar answered Jan 26 '26 22:01

Paulw11


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")
like image 44
vadian Avatar answered Jan 26 '26 23:01

vadian