2
votes

Say for example I have class like so and instead of making fields that I will assign to in the init method I just want to have implicitly unwrapped optionals.

class foo {
  willBeSomeBool: Bool!
  willBeSomeString: String!
}

I understand the reason for doing this is so that when I declare them they will have an initial value of nil and thus I don't need an init as all the class's fields have initial values. All I need to do is make sure I assign something to them before I try and access them otherwise I will get a fatal error.

So say we've assigned values to the fields and now we are in some method, what I'm asking is: why we need to forcefully unwrap the bool when we use it inside a conditional? I can access other implicitly unwrapped optionals and even the bool without doing so outside of a conditional.

func bar() {
  if willBeSomeBool! {
    ...
  }
}

func buzz() {
  print(willBeSomeString)
}

My best guess for this is because we can still check for nil on the implicitly unwrapped variable so in the context of a conditional it is treated as if it was just a normal optional, but like I said its my best guess, and maybe I'm missing something else?

1

1 Answers

3
votes

why we need to forcefully unwrap the bool when we use it inside a conditional

It's a historical issue. Once upon a time, in the early days of Swift, an Optional could be used as a condition as a way of asking whether it was nil. There is thus a residual worry that you might think that if willBeSomeBool is a nil test. Therefore you have to either test explicitly for nil or unwrap so that we have a true Bool, thus proving that you know what you're doing — and preventing you from misinterpreting your own results.

Look at it this way. You can't say if willBeSomeString. You can only say something more explicit, either if willBeSomeString == nil or if willBeSomeString == "howdy". So it is simplest to make willBeSomeBool obey that same pattern.