有人可以帮助我理解为什么我无法将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"。这是为什么?
答案 0 :(得分:4)
在分配财产时,您不需要(或想要)拆开财产。你只需直接引用它;
init(firstName: String, middleName: String, lastName: String)
{
self.firstName = firstName
self.middleName = middleName
self.lastName = lastName
}
当middleName
为nil
时(最初为),条件展开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")