Runtime error handling in Swift

前端 未结 2 1111
走了就别回头了
走了就别回头了 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-12 23:55

    Edit: This answer is not updated with swift 2.0. As swift now has error handling I have not updated the below answer. Some aspect of error handling will be updated in future with swift 3.0. You can follow this answer Error-Handling in Swift-Language

    Swift is made to be typeSafe language.It get error at compile time rather than waiting to cause at runtime.

    In first example you are using Optional.

    var test: String?
    

    First understand meaning of optional.When you specifying optional you are saying it could be nil or have no value.Now when you unwrapping test you are saying i know this value is not nil.Please unwrap it i am sure about that.So its your responsibility to see where it nil.If you are not sure about that than you should use optional binding here.When you are unsure about value always use if condition while unwrrapping

      if let notNilTest = test {
        //use notNilTest
      }
      else{
       //handle error
      }
    

    In second example it should make sense to have the runtime exception handling but you can easily get this with if condition having count.So in second example as developer you should use if condition to get count of array.

    From swift guide:

    If you try to use subscript syntax to retrieve or set a value for an index that is outside of an array’s existing bounds, you will trigger a runtime error. However, you can check that an index is valid before using it, by comparing it to the array’s count property. Except when count is 0 (meaning the array is empty), the largest valid index in an array will always be count - 1, because arrays are indexed from zero.

    They clearly mention about this and you should take care of these things to make your code less buggy.Some things they have provided and we should know about how to use these things.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题