swiftforced-unwrappingoptional-chaining

Force unwrap or use optional chaining to set property


Given an optional var pinImageView: UIImageView? which has properties that are set, I'm not sure which way is preferred to set the property. For example:

if let image = UIImage(named: "Pin") {
    pinImageView = UIImageView(image: image)
    pinImageView?.restorationIdentifier = "pin"
}

or

if let image = UIImage(named: "Pin") {
    pinImageView = UIImageView(image: image)
    pinImageView!.restorationIdentifier = "pin"
}

Solution

  • which way is preferred

    It is generally accepted that you should avoid ! (force unwrapping) which is just begging for a crash, so this use should be avoided:

    if let image = UIImage(named: "Pin") {
        pinImageView = UIImageView(image: image)
        pinImageView!.restorationIdentifier = "pin"
    }
    

    In this case, since you've just assigned pinImageView, force unwrapping it is safe, but it still raises red flags to you or anyone else who reads your code in the future. "Ugh, they're using force unwrap here. Could that crash? Well, could pinImageView be nil? No, it was just assigned in the previous line, so it's OK." Why put yourself and others through this thought process; avoid the ! whenever possible.

    This usage:

    if let image = UIImage(named: "Pin") {
        pinImageView = UIImageView(image: image)
        pinImageView?.restorationIdentifier = "pin"
    }
    

    is safer because it uses optional chaining to unwrap pinImageView and avoids the crash operator !, but it still unwrapping an optional variable.

    A third alternative:

    The reason the imageView is optional is that you've assigned it to an optional variable. If instead, you use a let constant to hold the object while you configure it, you can avoid filling your code with unwrapping code:

    if let image = UIImage(named: "Pin") {
        let imageView = UIImageView(image: image)
        imageView.restorationIdentifier = "pin"
        pinImageView = imageView
    }
    

    This method works well when you are assigning many properties to the object since you can avoid many unwrapping operators.

    Don't worry about the extra line of code. The compiler will optimize that out. Code for readability and clarity.