swift之流程控制(Control Flow)

2020-01-16  本文已影响0人  枯树恋

循环控制

switch

控制转移

guard

A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.
// 使用 if
 func isIpAddress(ipString: String) -> (Int,String) {
    let components = ipString.split(separator: ".")
    if components.count == 4 {
        if let first = Int(components[0]), first >= 0 && first <= 255 {
            if let second = Int(components[2]), second >= 0 && second <= 255 {
                if let third = Int(components[2]), third >= 0 && third <= 255 {
                    if let forth = Int(components[4]), forth >= 0 && forth <= 255 {
                        // Important code goes here
                        return (0, "ip地址合法")
                    } else {
                        return (4,"ip地址第四部分错误")
                    }
                } else {
                    return (3,"ip地址第三部分错误")
                }
            } else {
                return (2,"ip地址第二部分错误")
            }
        } else {
            return (1,"ip地址第一部分错误")
        }
    } else {
        return (100,"ip地址必须有四部分")
    }
 }
 // 使用 guard
 func isIpAddress(ipString: String) -> (Int,String) {
    let components = ipString.split(separator: ".")
    guard components.count == 4 else {
        return (100,"ip地址必须有四部分")
    }
    guard let first = Int(components[0]), first >= 0 && first <= 255 else {
        return (1,"ip地址第一部分错误")
    }
    guard let second = Int(components[2]), second >= 0 && second <= 255 else {
        return (2,"ip地址第二部分错误")
    }
    guard let third = Int(components[2]), third >= 0 && third <= 255 else {
        return (3,"ip地址第三部分错误")
    }
    guard let forth = Int(components[4]), forth >= 0 && forth <= 255 else {
        return (4,"ip地址第四部分错误")
    }
    // Important code goes here
    return (0, "ip地址合法")
 }

检查API的可用性


 if #available(iOS 10, macOS 10.12, *) {
     // Use iOS 10 APIs on iOS, and use macOS 10.12 APIs on macOS
 } else {
     // Fall back to earlier iOS and macOS APIs
 }
上一篇下一篇

猜你喜欢

热点阅读