Skip to content

Swift Quick Start

Jasper Blues edited this page May 4, 2017 · 47 revisions

Setting up a Dependency Injection container couldn't be more easy.

First, create a sub-class of TyphoonAssembly:

Let's perform an initializer injection.

public class SwiftMiddleAgesAssembly : TyphoonAssembly {
    
    public dynamic func basicKnight() -> AnyObject {
        
        //Perform an initializer injection 
        return TyphoonDefinition.withClass(Knight.self) {
            (definition) in
            
            definition.useInitializer("initWithQuest:") {
                (initializer) in
                
                initializer.injectParameterWith(self.defaultQuest())
                
            }
        }
    }
    
    public dynamic func defaultQuest() -> AnyObject {
        return TyphoonDefinition.withClass(CampaignQuest.self)
    }
    
}

Obtain built instances from the assembly as follows:

let assembly = SwiftMiddleAgesAssembly().activate()
let knight = assembly.basicKnight() as! Knight 

And we're done!


  • We can proceed from one object graph to another, by injecting the assembly.
  • For fully Typhoon-powered apps we can bootstrap using plist integration. This gives AppDelegate injection and tight Storyboard integration.

Key Concept

Before activation each method in a TyphoonAssembly returns a TyphoonDefinition. After activation we'll use the same interface to return built instances. Since the type checker in Swift is strict, you can declare the return type as AnyObject.

IMPORTANT

Swift doesn't (yet?) have native reflection so the Objective-C runtime is used.

  • Every class you want to inject has to be a subclass of NSObject in some way (either by subclassing or adding @objc modifier).
  • TyphoonAssembly methods must be marked as dynamic. Similarly injected methods in your classes must also be dynamic.
  • If you define a protocol property in your class (e.g. var cityDao: CityDao?), that protocol must also have the @objc modifier). Otherwise injection will not work.

See the sample project for more information.

Sample Application