gpt4 book ai didi

swift - 带有可选参数的类 Init - 不可能?

转载 作者:搜寻专家 更新时间:2023-11-01 05:55:12 25 4
gpt4 key购买 nike

有人可以帮助我理解为什么我无法将 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
}

关于swift - 带有可选参数的类 Init - 不可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49689007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com