Why to avoid forced unwrapping

前端 未结 3 1764
眼角桃花
眼角桃花 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条回答
  •  [愿得一人]
    2020-12-16 07:06

    There's nothing wrong with crashing a program if it actually has a bug...if you can not work your way around the crash

    But as @phillip-mills says in his comment:

    ...asked by people who use forced unwrapping without understanding that's what's causing the crash

    We often see examples where people force unwrap optionals that, for some unexpected reason, isn't there, and in that case it makes sense to try to unwrap the optional "gracefully.

    An Example of Bad Forced Unwrapping

    Lets say you have a backend service that gives you some JSON which you parse into a model object and present in a view.

    Lets say you have a model like this one:

    struct Person {
        let firstName: String?
        let lastName: String?
    }
    

    And in a UITableView you populate some cells with person objects. Something along the lines of:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //dequeue your cell
        //get your person element from some array
        //populate
        cell.firstNameLabel.text = person.firstName!
        cell.lastNameLabel.text = person.lastName! 
    
        return cell
    }
    

    At some point you probably will end up with a Person without a firstName (you can say that that is a problem with the backend and so on and so forth but....it'll probably happen :) ) If you force unwrap, your app will crash where it shouldn't be necessary. In this case you could have gotten away with a graceful unwrap

    if let firstName = person.firstName {
        cell.firstNameLabel.text = firstName
    }
    

    Or you could have used the Nil Coalescing Operator

    let firstName = person.firstName ?? ""
    

    Finally, as @rmaddy says in his answer

    Forced unwrapping is bad because your program is not guaranteed to be accessing an actual variable at the time of execution

    You can not always be sure that the data is what you expect it to be.

    And when you have the possibility to actually only do some operation if you're absolutely sure that the data you're operating on is valid, that is, if you've unwrapped it safely...it'd be stupid not to use that option :)

    Hope that helps you.

提交回复
热议问题