Alchemic - now with Swift

Swift   alchemic   iOS   announcement  

Yep. Just spent the last month or so playing with Swift for the first time and modifying Alchemic so that it can be used in Swift projects.

It proved an interesting project. In some respects Swift is more succinct than Objective-C meaning it takes less code. But in others it ended up needing more code. Mostly around runtime functionality.

One of the biggest differences is that in Swift there are no pre-processor macros. Alchemic for Objective-C make extensive use of pre-processor macros to make integrating it with your code simple. Some of these macros actually expand out into class methods. This enables Alchemic to avoid requiring you to to implement specific methods and allows you the freedom of placing the code where in the class bests suite you.

However, Swift doesn't have any way to generate code in the same way. So the best option turned out to be using one central method. Here's an example of using Alchemic in Swift:

import AlchemicSwift

class MyClass {

    var aDependency:SomeOtherClass

    public static func alchemic(cb:ALCBuilder) {
        AcRegister(cb, AcWithName("Instance name"))
        AcInject(cb, variable:"aDependency", type:SomeOtherClass.self)
    }
}

As you can see I've kept all the same names from the Objective-C macros and turned them into Swift functions. This makes switching from to the other quite simple. You can also see that when compared to the macros they are more 'wordy'. Unfortunately there is no way around this.

So take a look. I've added new documentation to help see how to use it.


Comments powered by Disqus