I have the following code (trying to avoid implicit unwrapping):
class MyTests: XCTestCase {
var viewController: ViewController
}
But I'm getting the following error:
Class 'MyTests' has no initializers
I fixed with this:
class MyTests: XCTestCase {
var viewController: ViewController
override init() {
self.viewController = ViewController()
super.init()
}
}
Would be a issue using init()
in XCTest class?
I'm using Swift 4, Xcode 9.2.
Every Swift developer runs into this error at some point. To resolve this error, you need to understand an important aspect of classes. Swift requires that the stored properties of a class receive an initial value during initialization.
An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }
I understand that you'd like to avoid implicitly unwrapping, but unfortunately (unless you want to go through the trouble of writing your own test runner), you don't have control over which initializer is called when the tests are run.
You could get around this by implicitly unwrapping, as you know, and setting the value of the property in setUp()
, which gets called before every test, so you can be sure the property will not be nil during your tests. This is relatively safe.
class MyTests: XCTestCase {
var viewController: ViewController!
override function setUp() {
super.setUp()
self.viewController = ViewController()
}
}
Alternatively, you could make the property lazy
, which means that it does not have to be implicitly unwrapped. This means that the property does not have to be initialized during object initialization so you don't need to write a new initializer, but will be initialized the first time it is accessed.
class MyTests: XCTestCase {
lazy var viewController: ViewController = {
return ViewController()
}()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With