1

I can't understand why I need to "force unwrap" variable type in it's declaration in my tests.

Let me give you an example to be more clear:

class testSomething: XCTestCase {

  var mockService: MockService!

  override func setUp() {
    mockService = MockService()
  }
  ...

So the goal obviously is to create a fresh instance of the mock service every time I run the test. I just don't understand why I need to declare this variable as MockService! type. What does the exclamation point after type really mean in this context?

Just to be clear, when I declare mockService: MockService Xcode complains that my test class does not have initializers

66o
  • 756
  • 5
  • 10
  • 2
    In this case: `mockService` is not initialized in place nor in the constructor, try to comment out the `!`. And take a look at this (second answer): http://stackoverflow.com/questions/24006975/why-create-implicitly-unwrapped-optionals here is a great overview of the use cases of `ImplicitlyUnwrappedOptional`s. – Dániel Nagy Sep 29 '15 at 07:37
  • `var mockService: MockService!` declares a variable with the type `ImplicitlyUnwrappedOptional`. It does not *"force unwrap variable type in it's declaration"*. – I would consider this as a duplicate of http://stackoverflow.com/questions/24006975/why-create-implicitly-unwrapped-optionals. – Martin R Sep 29 '15 at 07:54
  • yes, i didn't know the term `implicitly unwrapped optional` @DánielNagy, can you please post your comment as a reply and I will mark it as a best reply. – 66o Sep 29 '15 at 08:46

1 Answers1

1

A non-optional variable must be initialized in the declaration line

var mockService = MockService()

or in an init() method

var mockService : MockService

init() {
  mockService = MockService()
}

If this is not possible declare the variable as forced unwrapped and make sure that the variable is not nil whenever it's used. Then it behaves like a non-optional.

vadian
  • 274,689
  • 30
  • 353
  • 361