• Swift学习笔记-控制流(Control Flow)-提前退出(guard)


    if语句一样,guard的执行取决于一个表达式的布尔值。我们可以使用guard语句来要求条件必须为真时,以执行guard语句后的代码。不同于if语句,一个guard语句总是有一个else分句,如果条件不为真则执行else分局中的代码。

    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).")
    }
    greet(["name": "John"])
    // prints "Hello John!"
    // prints "I hope the weather is nice near you."
    greet(["name": "Jane", "location": "Cupertino"])
    // prints "Hello Jane!"
    // prints "I hope the weather is nice in Cupertino."
    

    如果guard语句的条件被满足,则在保护语句的封闭大括号结束后继续执行代码。任何使用了可选绑定作为条件的一部分并被分配了值的变量或常量对于剩下的保护语句出现的代码段是可用的。

    如果条件不被满足,在else分支上的代码就会被执行。这个分支必须转移控制以退出guard语句出现的代码段。它可以用控制转移语句如return,breakcontinue做这件事,或者它调用了一个不返回的方法或函数,例如fatalError()

    相比于可以实现同样功能的if语句,按需使用guard语句会提升我们代码的可靠性。 它可以使你的代码连贯的被执行而不需要将它包在else块中,它可以使你处理违反要求的代码接近要求。

  • 相关阅读:
    python 数据类型 基础第二天
    Python基础第一篇
    前言、入门程序、常量、变量
    win10打开移动热点让手机连接上网教程
    win10移动热点问题
    博客园快速美化
    Idea提示没有符号类错误解决
    mybatis复习01
    test
    d190305面试题01总结
  • 原文地址:https://www.cnblogs.com/emmet7life/p/4898657.html
Copyright © 2020-2023  润新知