swift guard在使用=运算符时如何判断真假

How does swift guard determine true or false when using = operator

通过阅读语言指南 (developer.apple.com) 学习 swift 3.1。我了解到 swift 中的赋值运算符 (=) 不是 return 值。在 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).")
}

我的问题是,如果“=”运算符没有 return 值,则:

guard let name = person["name"] else {
    return
}  

守卫如何确定 name = person["name"] 是真还是假,并根据此转到其他和 return?

正如@Hasmish 指出的那样,let name = person["name"] 是一个 optional-binding-condition。当右侧不是 nil 时,它的计算结果为真,并且具有将包装值绑定到左侧标识符的副作用。

optional-binding-condition与右边是否true/false无关。

let optionalBool: Bool? = false
guard let bool = optionalBool else {
    fatalError("This will never be called, because `optionalBool` is not `nil`")
}

事实上,正如您所展示的,右侧甚至不必是 Bool

守卫的目的是断言一个值不是零,如果是,则保证退出当前范围。这允许在您的函数的其余部分使用该值,并允许您的 "golden path" 不嵌套在多个 if 语句中。

您可以使用 if-let 语法执行类似的操作,但它不保证必须退出范围或在其自身范围之外提供受保护的值。

guard let name = person["name"] else {
    return
}
// name available here!

对比

if let name = person["name"] {
    // name available here
} else {
    // name not available here
}

// name not available here either

所有这些都是基于if/guard语句是否可以保证值的存在,而不是真实性。