I am working on developing an application in Swift. I wanted to create a system for an application that would allow you to freely communicate between objects, and one strategy (which I have successfully used in other languages) was to create what I call the factory instance. This is pretty simple, and here is the main implementation I came across in Swift:
import Foundation private var typeGenerators = Dictionary<String, InstanceFactory.GeneratorCallback>() public class InstanceFactory: NSObject { public typealias GeneratorCallback = () -> AnyObject! public class func registerGeneratorFor(typeName: String, callback: GeneratorCallback) { typeGenerators[typeName] = callback } public class func instanceOf(typeName: String) -> AnyObject! { return typeGenerators[typeName]?() } }
The idea is that when an instance of an object needs access to another instance of the object, and not to create that instance, which would connect the two objects more tightly, the first object would be postponed to factory to provide the necessary instance by calling the instanceOf method. The factory will know how to provide different types of instances, because these types will be registered with the factory and provide a closure that the instance could generate.
The trick is how to get classes to register with factory. I had previously done a similar factory in Objective-C, and the way I got the registration to work was to override the + load method for each class that needs to be registered with factory. This worked fine for Objective-C, and I figured it could work for Swift, as I would limit the factory to only providing objects derived from NSObject. It turned out that I got this to work, and I spent a lot of effort developing classes to use the factory.
However, after upgrading to Xcode 6.3, I found that Apple had banned the use of the load class method in Swift. Without this, I donβt know about the mechanism that allows classes to automatically register with the factory.
I am wondering if there is another way to make registration work.
What alternatives exist that could allow classes to register with the factory, or what other methods could they use to perform the same loose coupling as factory?
source share