我仍然遇到选项问题,Apple 制作的示例对我来说并不清楚。我明白:
- 1 - optional 是一种数据类型,所以 Int? 还是字符串?是可选项,不是 Int 或 String
- 2 - optional 可以是变量,而不是常量,只要是可选的,可以是 nil 或其他
- 3 - 为了使用它们,你需要打开它们
4 - 您可以使用可选链接来执行检查(如何决定是展开还是链接?)
- A)如何在第二个打开圣诞老人?
- B) 展开后如何在其他函数中使用该变量?
- C)如何通过可选链接来面对同样的例子?
提前致谢
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")
}