有人能帮助我理解为什么我不能将middlename参数设置为一个值吗?我已经声明它是可选的,但是每当我试图初始化它时,总是在getFullName()函数中的guard语句中得到nil。

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”。为什么?

最佳答案

分配属性时不需要(或不希望)展开该属性。你只是直接提到它;

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
}

10-08 12:10