zoukankan      html  css  js  c++  java
  • 控制流(swift)

    检测API是否可用

    if #available(iOS 9, OSX 10.10, *) {
        // 在 iOS 使用 iOS 9 APIs , 并且在 OS X 使用 OS X v10.10 APIs
    } else {
        // 回滚至早前 iOS and OS X 的API
    }
    

     以上可用性条件指定在iOS,if段的代码仅仅在iOS9及更高可运行;在OS X,仅在OS X v10.10及更高可运行。最后一个参数,*,是必须的并且指定在任何其他平台上,if段的代码在最小可用部署目标指定项目中执行。

    在它普遍的形式中,可用性条件获取了平台名字和版本的清单。平台名字可以是iOSOSXwatchOS。除了特定的主板本号像iOS8,我们可以指定较小的版本号像iOS8.3以及 OS X v10.10.3。

    if #available(`platform name` `version`, `...`, *) {
        `statements to execute if the APIs are available`
    } else {
        `fallback statements to execute if the APIs are unavailable`
    }
    

    提前退出

    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."
    

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

  • 相关阅读:
    周记(2015-11-30 -- 2015-12-05)
    周记(2015-11-22 -- 2015-11-27)
    周记(2015-11-15 -- 2015-11-20)
    周记(2015-11-01 -- 2015-11-06)
    设备与主机的攻击日志类型分析总结
    OWASP十大攻击类型详解
    乌云TOP 10 简单介绍
    《启示录》读书笔记三
    百度地图和定位
    获取Android studio的SHA1值
  • 原文地址:https://www.cnblogs.com/wlsxmhz/p/5993189.html
Copyright © 2011-2022 走看看