Swift编程

使用 guard 来改善你的条件判断

2020-01-24  本文已影响0人  码农UP2U

今天学了 极客时间张杰 老师的 Swift,今天看的内容是 guard 关键字,说实话感觉暂时没有感觉出来它的好处。

guard

检查 api 的可用性

这是 guard 关键字使用的实例

示例

课程中讲了一个反例,反例如下:

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[1]), second >= 0 && second <= 255 {
                if let third = Int(components[2]), third >= 0 && third <= 255 {
                    if let fourth = Int(components[3]), fourth >= 0 && fourth <= 255 {
                        return (0, "ip 地址合法")
                    } else {
                        return (4, "ip 地址第四部分不对")
                    }
                    
                } else {
                    return (3, "ip 地址第三部分不对")
                }
            } else {
                return (2, "ip 地址第二部分不对")
            }
        } else {
            return (1, "ip 地址第一部分不对")
        }
    } else {
        return (100, "ip 地址必须有四部分")
    }
}

print(isIpAddress(ipString: "127.0.0.1"))

看到反例的写法以后,又给出了使用 guard 关键字解决的方法,代码如下:

func isIpAddress1(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[1]), second >= 0 && second <= 255 else {
        return (2, "ip 地址第二部分不对")
    }
    
    guard let third = Int(components[2]), third >= 0 && third <= 255 else {
        return (3, "ip 地址第三部分不对")
    }
    
    guard let fourth = Int(components[3]), fourth >= 0 && fourth <= 255 else {
        return (4, "ip 地址第四部分不对")
    }
    
    return (0, "ip 地址合法")
}

print(isIpAddress1(ipString: "127.0.0.1"))

说实话,我真没感觉到它的好用之处,对于第一个反例,通常我们也不会那样写代码,通常我们的写法是:

func isIpAddress(ipString: String) -> (Int, String) {
    let components = ipString.split(separator: ".")
    
    if components.count != 4 {
        return (100, "ip 地址必须有四部分")
    }

    if () {
    }

也就是让尽早的不合理提早的返回,其实 guard 也是这样做了。所以,没有太多的体会到 guard 的用法。



我的微信公众号:“码农UP2U”
上一篇 下一篇

猜你喜欢

热点阅读