当前位置: 代码迷 >> 综合 >> Day10:guard 语句
  详细解决方案

Day10:guard 语句

热度:56   发布时间:2023-09-29 19:10:26.0
  • guard 语句,类似if语句,基于布尔值表达式来执行语句。使用guard语句来要求一个条件必须是真才能执行guard之后的语句。与if语句不同,guard语句总是一个else分句--else分句里的代码会在条件不为真的时候执行。
  • 检查API的可用性。
  1. swift拥有内置的对API可用性的检查功能,它能够确保你不会被拒的使用里对部署目标不可用的API。
  2. 你可以使用if或者guard语句中使用一个可用行条件来有条件的执行代码,基于在运行时你想用的哪个API是可用的。
  • 【代码演示】
    //1、guard 语句
    func checkIPAddress(ipAddr:String) ->(Int,String){let compoments = ipAddr.split(separator: ".")if compoments.count == 4{if let first = Int(compoments[0]),first >= 0 && first < 256 {if let second = Int(compoments[1]),second >= 0 && second < 256 {if let third = Int(compoments[2]),third >= 0 && third < 256 {if let four = Int(compoments[2]),four >= 0 && third < 256 {return (0,"success")}else{return (4,"this four compoments is wrong")}}else{return (3,"this third compoments is wrong")}}else{return (2,"this second compoments is wrong")}}else{return (1,"the first compoments is wrong")}}else{return (100,"the is address must four compoments")}
    }print(checkIPAddress(ipAddr: "127,1.1"))func checkIPAddressGuard(ipAddr:String) ->(Int,String){let compoments = ipAddr.split(separator: ".")guard compoments.count == 4 else{return (100,"the is address must four compoments")}guard let first = Int(compoments[0]),first >= 0 && first < 256 else {return (1,"the first compoments is wrong")}guard let second = Int(compoments[1]),second >= 0 && second < 256  else {return (2,"this second compoments is wrong")}guard let third = Int(compoments[2]),third >= 0 && third < 256  else {return (3,"this third compoments is wrong")}guard let four = Int(compoments[2]),four >= 0 && third < 256 else {return (4,"this four compoments is wrong")}return (0,"success")
    }print(checkIPAddressGuard(ipAddr: "127,1.1"))