简体   繁体   中英

How to inject dependency via protocol in Typhoon using Swift?

I have a problem with Typhoon dependency injection framework. My viewcontroller MainViewController depends on dataProvider property that I want to declare as AnyObject corresponding to protocol DataProviderProtocol

class MainViewController: UIViewController {

   // Compiler error here
   var dataProvider : DataProviderProtocol!
   // something more
}

protocol DataProviderProtocol {
   func fetchAllBanks(closure : ([BankObject]) -> Void)
}

class TestDataProvider: NSObject, CEDataProviderProtocol {

   func fetchAllBanks(closure : ([CEBankObject]) -> Void) {
      var resultBanks = ///////code that creates test data
      closure(resultBanks);
   }

I want this dataProvider property to be injected by the Typhoon and initialized to the corresponding instance of class TestDataProvider , that implements this protocol. But I also have RealDataProvider that also corresponds to the DataProviderProtocol and might be used sometimes

But this code crashes with the message

Can't inject property 'dataProvider' for object ''. Setter selector not found. Make sure that property exists and writable'

I can inject this property without crashes if I use the property class of TestDataProvider , but this disables the ability to inject different DataProviderProtocol implementations.

I understand this this crash happens because DataProviderProtocol property type is not NSObject successor. But I just can't find a way to declare property as NSObject<DataProviderProtocol> in Swift

I would appreciate any help

PS My Assembly class

public class CEAppAssembly:TyphoonAssembly {

   //uiviewcontrollers' components assembly
   var mainComponentsAssembly : CEMainComponentsAssembly!


   /**
    UI Dependencies
   **/

   public dynamic func mainViewController() -> AnyObject {
      return TyphoonDefinition.withClass(MainViewController.self) {
         (definition) in

         definition.injectProperty("dataProvider", with: self.mainComponentsAssembly.dataProvider())
      }
   }

Typhoon uses the Objective-C run-time introspection and dynamic features. Therefore:

  • Protocols must be marked with the '@objc' directive.
  • Types incompatible with Objective-C (ie 'pure swift') can't be injected.

There's more information about this in the Quick Start guide. If you're still having trouble after reviewing and making those changes, let us know.

We plan to release a Pure Swift version of Typhoon in the near future.

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