Swift's guard keyword

前端 未结 13 2322
一整个雨季
一整个雨季 2020-11-27 09:03

Swift 2 introduced the guard keyword, which could be used to ensure that various data is configured ready to go. An example I saw on this website demonstrates a

13条回答
  •  暖寄归人
    2020-11-27 09:52

    Guard statement going to do . it is couple of different

    1) it is allow me to reduce nested if statement
    2) it is increase my scope which my variable accessible

    if Statement

    func doTatal(num1 : Int?, num2: Int?) {
      // nested if statement
        if let fistNum = num1 where num1 > 0 {
            if let lastNum = num2 where num2 < 50 {
    
              let total = fistNum + lastNum
            }
        }
     // don't allow me to access out of the scope 
     //total = fistNum + lastNum 
    }
    

    Guard statement

    func doTatal(num1 : Int?, num2: Int?) {
       //reduce  nested if statement and check positive way not negative way 
        guard let fistNum = num1 where num1 > 0 else{
          return
        }
        guard  let lastNum = num2 where num2 < 50 else {
         return
        }
        // increase my scope which my variable accessible
        let total = fistNum + lastNum
    
    }
    

提交回复
热议问题