As RobberR writes above, you could just use self
for accessing static function of self
, and self.init(...)
for your factory example. Note that you still must specify MyClass
as return type in your factory method.
As an alternative, more generic approach, you could let your class conform to a factory protocol which contains a default implementation for the factory method. With this, the static factory method isn't tied to any specific class, but can however be accessed by any class conforming to the factory protocol (and an additional help protocol for common initializers).
Factory setup:
protocol FactoryInitializers {
var commonProperty : Int { get set }
init(commonProperty: Int)
}
protocol FactoryMethods {
typealias T: FactoryInitializers
static var defaultStaticCommonProperty : Int { get }
}
extension FactoryMethods {
static func getInstance() -> T {
return T(commonProperty: defaultStaticCommonProperty)
}
static func getInstanceFor(commonProperty commonProperty: Int) -> T {
return T(commonProperty: commonProperty)
}
}
protocol Factory : FactoryMethods, FactoryInitializers { }
Example class conformances:
class MyClass : Factory {
typealias T = MyClass
static var defaultStaticCommonProperty : Int = 1
var commonProperty : Int = 0
required init(commonProperty: Int) {
self.commonProperty = commonProperty
}
}
class MyOtherClass : Factory {
typealias T = MyOtherClass
static var defaultStaticCommonProperty : Int = 10
var commonProperty : Int = 0
required init(commonProperty: Int) {
self.commonProperty = commonProperty
}
}
Example usage:
var foo = MyClass.getInstance()
print(foo.dynamicType) // "MyClass"
print(foo.commonProperty) // 1
foo = MyClass.getInstanceFor(commonProperty: 5)
print(foo.commonProperty) // 5
var bar = MyOtherClass.getInstance()
print(bar.dynamicType) // "MyOtherClass"
print(bar.commonProperty) // 10
self()
? I get some errors saying I needself.init
, and when I do I get some other error that I need arequired
initializer... – Cappuccino