我仍然遇到选项问题,Apple的例子对我来说并不清楚。我明白了:
4 - 您可以使用可选链接来执行检查(如何确定解包或链接?)
提前致谢
var santa : String?
println(santa)
if let santaExists = santa {
println("Santa exists! Santa is: \(santa)")
}
else {
println("Santa is missing! Santa is: \(santa) or not set") //Santa is missing! Santa is: nil or not set
}
santa = "I am here!"
if let santaExists = santa {
println("Santa exists! Santa is: \(santa)") //Santa exists! Santa is: Optional("I am here!)
}
else {
println("Santa is missing! Santa is: \(santa) or not set")
}
编辑:解决方案
var santa : String?
println(santa)
if let santaExists = santa {
println("Santa exists! Santa is: \(santa)")
}
else {
println("Santa is missing! Santa is: \(santa) or not set") //Santa is missing! Santa is: nil or not set
}
santa = "I am here!"
//first way to unwrap, with a " ! "
if let santaExists = santa {
println("Santa exists! Santa is: \(santa!)") //Santa exists! Santa is: I am here! (santa unwrapped)
}
else {
println("Santa is missing! Santa is: \(santa) or not set")
}
//second way to unwrap don't use santa, but the new constant
if let santaExists = santa {
println("Santa exists! Santa is: \(santaExists)") //Santa exists! Santa is: I am here! (santa unwrapped by let)
}
else {
println("Santa is missing! Santa is: \(santa) or not set")
}
答案 0 :(得分:1)
首先,在创建变量时,例如圣诞老人,请把第一个字母写成小写,即圣诞老人。
要在第二个if语句中使用unwrapped santa,添加一个感叹号,这告诉编译器你知道这个变量不是nil。
println("Santa exists! Santa is: \(Santa!)")
您还可以使用下面的代码,因为您已将变量Santa的内容设置为SantaExist作为常量
if let SantaExist = Santa {
println("Santa exists! Santa is: \(SantaExist)") //Santa exists! Santa is: Optional("I am here!)
}
else {
println("Santa is missing! Santa is: \(Santa) or not set")
}
对于可选链接,这只是用问号代替感叹号,因此如果它是nil,它将“优雅地失败”而不是使应用程序崩溃。