66o
66o

Reputation: 756

Swift: Why do I need to unwrap non optional variable in declaration

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

Upvotes: 1

Views: 655

Answers (1)

vadian
vadian

Reputation: 285290

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.

Upvotes: 1

Related Questions