【发布时间】:2017-04-09 13:42:19
【问题描述】:
通过阅读语言指南 (developer.apple.com) 学习 swift 3.1。我了解到,在 swift 中,赋值运算符 (=) 不会返回值。在control flow章节中得到了一个guard语句的例子:
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).")
}
我的问题是如果 '=' 运算符不返回值,那么:
guard let name = person["name"] else {
return
}
guard 如何判断 name = person["name"] 是真还是假,并根据此判断 go to else 并返回?
【问题讨论】:
-
正确,
=不返回任何值。但是person["name"]返回一个可选值,因此guard let正在将该值可选绑定到相关变量。所以guard let语句是说“guard确保person["name"]返回一个值,如果是这样,将name变量设置为该未包装的值”。但是,如果不是(即如果person["name"]返回nil),那么它将执行else子句中的内容(例如,在这种情况下为return) -
@Rob,所以对于守卫语句:
guard let <condition>条件 (name = person["name"]) 不必为真或假? -
@HassanMakarov 这不是
guard let <condition>——它是guard <condition>。<condition>可以是评估为Bool的表达式、可用性条件、案例条件,或者在这种情况下是可选绑定条件——通常具有语法let <identifier> = <expression>。这确实不意味着它评估为Bool。如果您想要更详细的细分,请参阅the grammar section of the language guide。 -
参见Optional Binding,它展示了它是如何与
if语句一起工作的,这与提前退出guard-else语句的想法相同。
标签: swift guard-statement