Why to avoid forced unwrapping

前端 未结 3 1765
眼角桃花
眼角桃花 2020-12-16 06:21

There are cases where you forgot to set a value (so it\'s actually a bug), and running the program with forced unwrapping can crash the problem, and that can allow you to tr

3条回答
  •  -上瘾入骨i
    2020-12-16 07:03

    Forced unwrapping is bad because your program is not guaranteed to be accessing an actual variable at the time of execution. When this happens your program might be attempting to perform a mathematical calculation on a number that doesn't exist, and your app would crash. Your point of in the development phase if it crashes you would be able to narrow down why the crash happened and fix the issue of it being nil at runtime for your development phase, but what about in production?

    For example, if you were retrieving some sort of number from a web service you may want to compare this number to something local, maybe a version number:

    if let json = try? JSONSerialization.jsonObject(with: responseData, options: .allowFragments) as? [String: Any], 
       let serverAPIVersion:NSNumber = json["API_Version_Number"] as? NSNumber {
    
        if self.currentAPIVersion.uintValue < serverAPIVersion.uintValue {
           self.updateVersionWith(number: serverAPIVersion)
        }
    
     }
    

    In the code above we are safely unwrapping the "API_Version_Number" from the JSON we get from the server. We are safely unwrapping because if there weren't a value for "API_Version_Number" then when we would try to do the comparison to the current version, the program would crash.

    // This will crash if the server does not include "API_Version_Number in json response data
    let serverAPIVersion:NSNumber = json["API_Version_Number"] as! NSNumber
    

    And in production there are things out of your control (many times a server side issue) that may lead to unpopulated variables. That is why it is best to conditionally unwrap to gain access to values safely in your code to keep things from crashing at execution time.

提交回复
热议问题