Has*_*req 1 swift guard-statement
通过阅读语言指南 (developer.apple.com) 学习 swift 3.1。我了解到在 swift 中赋值运算符 (=) 不返回值。在控制流章节中得到了一个保护语句的例子:
func greet(person: [String: String]) {
guard let name = person["name"] else {
return
}
print("Hello \(name)!")
guard let location = person["location"] else {
print("I hope the weather is nice near you.")
return
}
print("I hope the weather is nice in \(location).")
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果 '=' 运算符不返回值,则:
guard let name = person["name"] else {
return
}
Run Code Online (Sandbox Code Playgroud)
守卫如何确定name = person["name"]是真还是假,并根据它转到 else 并返回?
守卫的目的是断言一个值是非零的,如果是,则保证退出当前范围。这允许在整个函数的其余部分使用该值,并允许您的“黄金路径”不会嵌套在多个 if 语句中。
您可以使用 if-let 语法做类似的事情,但它不保证必须退出范围或在其自己的范围之外提供受保护的值。
guard let name = person["name"] else {
return
}
// name available here!
Run Code Online (Sandbox Code Playgroud)
对比
if let name = person["name"] {
// name available here
} else {
// name not available here
}
// name not available here either
Run Code Online (Sandbox Code Playgroud)
所有这一切都是基于 if/guard 语句是否可以保证某个值的存在,而不是基于真实性。