Skip to content

Swift Quick Start

jasperblues edited this page Sep 9, 2014 · 33 revisions
let Application = Swift as TheCoursingRiver
//With all the force of a great Typhoon!

Setting up a Dependency Injection for your Swift application is easy!

  • First, let's bootstrap Typhoon.
  • Create a sub-class of TyphoonAssembly, and define your AppDelegate, as follows:
public class ApplicationAssembly : TyphoonAssembly {
    
    public dynamic func appDelegate() -> AnyObject {
        return TyphoonDefinition.withClass(AppDelegate.self) {
            (definition) in
            
            definition.injectProperty("assembly", with: self)
        }
    }    
}

###Create an entry in your application's plist to register the assembly:


###And now, add the following property to your AppDelegate:

var assembly : ApplicationAssembly?

###Now let's perform an Initializer Injection

  • Edit the ApplicationAssembly you defined above to include the following definitions:
    public dynamic func basicKnight() -> AnyObject {
        
        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)
    }

###Resolve the component from the Typhoon as follows:

   func application(application: UIApplication, 
       didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) 
       -> Bool {
        
        //Code-completion + no 'magic strings'  
        var knight : Knight = assembly.basicKnight()
        
        // . . continue setting up App        

        return true
    }

And we're done!

#Key Concept

  • At build-time our Assembly interface returns TyphoonDefinitions
  • At run-time we use this interface to resolve built components.

#Other Notable Points
  • The assembly interface can be injected on any definition in the assembly, not just the AppDelegate
  • Instead of registering the assemblies in the app's list, Typhoon can also be manually bootstrapped, by instantiating a TyphoonComponentFactory. This is useful when introducing Typhoon into a legacy application. (Hopefully your Swift applications aren't this yet ;) ).
  • If you've used Typhoon with Objective-C, you probably know that you can cast your TyphoonComponentFactory to your assembly interfaces. This provides code-completion, and allows the use of IDE refactoring tools. Swift's strict type checking doesn't allow this, however you can inject the assembly onto any definition, as we did with the AppDelegate above.

#User Guide

(Swift user guide coming soon)