Skip to content

Swift Quick Start

Jasper Blues edited this page Feb 14, 2015 · 47 revisions

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

First, create a sub-class of TyphoonAssembly as follows:

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 container as follows:

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

And we're done!



Key Concept: Before activation each method returns in a TyphoonAssembly returns a TyphoonDefinition. After activation we'll use the same interface to return built instances. Since the main use for your assembly interfaces will be emitting built components, you can declare the return type as the type being built.

  • IMPORTANT! Every class you want to inject has to be a subclass of NSObject in some way (either by subclassing or adding @objc modifier). Also 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