Best Practice For Unwrapping Many Optionals

Best practice for unwrapping many optionals

Best practice for unwrapping many optionals

In general, you should avoid the force-unwrap operator unless you can 100% prove that the value will never be , which should be a tiny minority of the time (usually when loading files included inside your application's bundle). This clearly isn't the case here, since the value is nil, so you should either use or to unwrap the value, handling the case where it is , or you can use the operator to provide a default value like so:

Depending on what your object is supposed to do, it's also possible that it might actually be appropriate for it to contain a value for .

In this case, you may just want to declare its property as an optional by adding an to the end of its type:

In this case, you would unwrap the property later, when it comes time to use it.

Top 3 Ways to Best Handle Optionals