Search code examples
iosswifttyphoon

Manually convert TyphoonConfig


Basically i want to do something like this.

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

        definition.useInitializer("initWithHost:") {
            (initializer) in

            let url: NSURL! = TyphoonConfig("someUrl") as NSURL
            initializer.injectParameterWith(url.host)
        }
    }
}

But TyphoonConfig() is from Type TyphoonInjectionByConfig.

Is it possible to convert the TyphoonConfig Object manually, or do i need to inject it and it will converted then?


Solution

  • TyphoonConfig allows defining config in an external configuration file in either .properties, .plist or .json format. Since these formats provide limited types, Typhoon provides built-in type converters to transform the string representation to the required type. In-built converters exist for primitives and common types like NSURL, UIColor. You can also define your own.

    To externalize an NSURL, create a definition referencing your config:

    /*
     * A config definition, referencing properties that will be loaded from a plist. 
     */
    public dynamic func config() -> AnyObject {
    
        return TyphoonDefinition.configDefinitionWithName("Configuration.plist")
    }
    

    Use it:

    public dynamic func someClass() -> AnyObject {
        return TyphoonDefinition.withClass(SomeClass.self) {
            (definition) in
    
            definition.useInitializer("initWithHost:") {
                (initializer) in
    
                initializer.injectParameterWith(TyphoonConfig("someUrl"))
            }
        }
    }
    

    And create the config file as follows.

    <plist version="1.0">
    <dict>
        <key>someUrl</key>
        <string>NSURL(http://api.worldweatheronline.com/free/v2/weather.ashx)</string>
        <key>api.key</key>
        <string>dbaffee6eb10d4fdc1a5d333554e4</string>
        <key>days.to.retrieve</key>
        <string>NSNumber(5)</string>
    </dict>
    </plist>
    

    Note that we declare the value as NSURL(http://api.worldweatheronline.com/free/v2/weather.ashx), meaning Typhoon will look in its registry of converters for one that can handle NSURL. You can also register your own converters, as described here.