I hope markdown is supported in these mails. :)
A few month ago I build a singleton generator with the help of protocols (just for fun). As you all know a true singleton will hide its init(), but right know there is no Access control for protocols. This might be a good feature for other code abstraction too.
Any feedback is welcome.
Here is my little implementation.
public protocol SingletonType { /* private */ init() } // wait for this feature to create a true singleton
private var singletonInstances = [String: SingletonType]()
public extension SingletonType {
typealias SingletonInstance = Self
typealias SingletonMetatype = Self.Type
public static var getSingleton: SingletonInstance { return setSingleton { $0 } }
public static var setSingleton: SingletonMetatype { return self }
public static func setSingleton(setter: (_: SingletonInstance) -> SingletonInstance) -> SingletonInstance {
guard let instance = singletonInstances["\(self)"] as? Self else {
return setInstance(self.init(), withSetter: setter, overridable: true)
}
return setInstance(instance, withSetter: setter, overridable: false)
}
private static func setInstance(var instance: Self, withSetter setter: (_: Self) -> Self, overridable: Bool) -> Self {
// I will have to fix `var instance` in Swift 3.0 :/
instance = restoreInstanceIfNeeded(instance1: instance, instance2: setter(instance), overridable: overridable)
singletonInstances["\(self)"] = instance
return instance
}
private static func restoreInstanceIfNeeded(instance1 i1: Self, instance2 i2: Self, overridable: Bool) -> Self {
guard i1.dynamicType is AnyClass else { return i2 }
return ((i1 as! AnyObject) !== (i2 as! AnyObject)) && !overridable ? i1 : i2
}
}
infix operator « { associativity none }
func « <Instance: SingletonType>(type: Instance.Type, newInstance: Instance) -> Instance {
return type.setSingleton { (_) -> Instance in newInstance }
}
···
—
Regards Adrian