Runtime error handling in Swift

前端 未结 2 1241
走了就别回头了
走了就别回头了 2021-02-12 23:07

I am fully aware that Swift doesn\'t have a try/catch mechanism to catch exceptions (OK, Swift 2.0 now supports them). I also understand that many API methods return a NSError t

2条回答
  •  轮回少年
    2021-02-13 00:06

    Consider using a guard statement instead of multiple if lets.

    var arr = [0,1,2]
    for i = 0...3 {
        Guard arr[i] != nil else {
            Continue
        }
        println(arr[i]) //oops!
    }
    

    Or instead of

    if let x = some value {
        If let y = someOtherVal {
            If let z = yetanotherVal {
                Product = x * y* z
            }
        }
    }
    

    Is not nearly as neat as:

    Let x = someVal
    Let y = someOtherVal
    Let z = yetAnotherVal
    
    Guard x != nil,
      y != nil,
      z != nil
    Else {
      Return
    }
    
    Product = x * y * z
    

提交回复
热议问题