Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2016-12-21

Value of optional type Bool not unwrapped | Swift Gotcha

Ever come across the following error message?



It occurs when we do something like this:

      [weak self]
      ....
      if self?.isValidPrivateKey(atPath: keyfilepath) {

The "Fix-it"solution from xcode is the following:

      if (self?.isValidPrivateKey(atPath: keyfilepath))! {

And indeed the error message goes away, everything fine?

Nope, don't let that fool you. The entire purpose of the weak "self?" reference is now gone. When self is indeed nil you will get an exception at runtime.

The proper thing to do is the following (choosing either "false" or "true" based on the case at hand:

     if self?.isValidPrivateKey(atPath: keyfilepath) ?? false {

Now the choice of what to do if self is indeed nil is made explicit and won't cause any problems at runtime.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment