简体   繁体   中英

Non-optional var in swift UIViewController subclass

import Foundation
import RentalsService

class RentalsViewController: UIViewController {

    var rentalService: Rentals

    init(rentalService: Rentals) {
        self.rentalService = rentalService
        super.init(nibName: "RentalsViewController", bundle: NSBundle.mainBundle())

    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder) // problem here
    }

}

I want rentalService variable to be non-optional. ie you can't have a rentalsVC without the service. However, I'm forced to declare init(NSCoder) - but I don't have access to a rental service implementation at this point.

Rentals is a protocol, and I'm using dependency injection - so one doesn't create the dependency inside the class.

Anyone got any clever ideas to overcome this? Or what is the preffered pattern / best practice?

You can do this if you don't want to support NSCoding:

required init(coder: NSCoder) {
  fatalError("NSCoding not supported")
}

As referenced here: https://stackoverflow.com/a/25128815/2611971

Depending on which DI framework you're using, the way I'd fix it is by using setter injection rather than constructor injection.

In that case you have to either provide an initial fake value to the property at initialization time, or convert the property to optional. In the latter case, I'd declare it as implicitly unwrapped:

var rentalService: Rentals!

to avoid unwrapping it explicitly at every usage.

Another solution, which I am using in my own DI framework, is to initialize properties lazily and inline, for example:

private lazy var _router: IRouter = { Injector.instance.instanceForType(IRouter.self) as IRouter }()

Here I know the interface, and I ask the injector to provide me an instance of whichever the bound type is. During app initialization I link interfaces to implementation statically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM