具有可选参数的类Init - 不可能吗?

时间:2018-04-06 08:54:48

标签: swift

有人可以帮助我理解为什么我无法将middleName参数设置为值吗?我已将其声明为可选项,但每当我尝试初始化它时,我总是在getFullName()函数中运行保护语句。

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")

打印时返回的值为" Foo Foobar"。这是为什么?

2 个答案:

答案 0 :(得分:4)

在分配财产时,您不需要(或想要)拆开财产。你只需直接引用它;

init(firstName: String, middleName: String, lastName: String)
{
    self.firstName = firstName
    self.middleName = middleName
    self.lastName = lastName
}

middleNamenil时(最初为),条件展开self.middleName?失败,因此未执行作业。

有条不紊地展开self.middleName实际上是一种简单的说法

if self.middleName != nil {
    self.middleName = middleName
}

由于middleName是可选的,因此您可能也希望初始化参数可选:

init(firstName: String, middleName: String?=nil, lastName: String)
{
    self.firstName = firstName
    self.middleName = middleName
    self.lastName = lastName
}

答案 1 :(得分:1)

如果属性是可选的,你必须在init方法中选择相应的参数,否则将属性声明为可选是毫无意义的。

init(firstName: String, middleName: String?, lastName: String)
{
    self.firstName = firstName
    self.middleName = middleName
    self.lastName = lastName
}

您甚至可以将nil指定为默认,以便省略参数

init(firstName: String, middleName: String? = nil, lastName: String)
{
    self.firstName = firstName
    self.middleName = middleName
    self.lastName = lastName
}

let person = Person(firstName: "Foo", lastName: "FooBar")