30使用guard改善条件判断

该博客介绍了如何使用Swift编写一个函数checkIPAddress2,用于检查IP地址是否符合规范,包括四个部分且每个部分的值在0-255之间。通过示例展示了函数的调用结果和错误处理过程。

判断IP地址

func checkIPAddress2(ipAddr:String) ->(Int, String){
            let compoments = ipAddr.split(separator: ".")
            
            guard compoments.count == 4 else {
                return (100,"the ip address must has four compoments")
            }
            guard let first = Int(compoments[0]),first >= 0 && first < 256 else{
                return (1,"this first compoment is wrong")
            }
            guard let second = Int(compoments[1]),second >= 0 && second < 256 else{
                return (2,"this second compoment is wrong")
            }
            guard let third = Int(compoments[2]),third >= 0 && third < 256 else{
                return (3,"this third compoment is wrong")
            }
            guard let fourth = Int(compoments[3]),fourth >= 0 && fourth < 256 else{
                return (4,"this fourth compoment is wrong")
            }
            return(0,"")
        }
        print(checkIPAddress2(ipAddr: "127.0.-1.0"))

print:(3, "this third compoment is wrong")
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值