Reputation: 6790
I am trying to create a class method which optionally returns an (already instantiated) instance of the class.
I'm thinking of something like writing the memory address of the instantiated class to a user default key and then trying to return the object at that address but I'm not sure if that's a correct approach or how to do that.
class MyClass {
let myProperty: String
required init(myProperty: String) {
self.myProperty = myProperty
}
class func currentClass() -> MyClass? {
return nil
}
}
let aNewClass = MyClass(myProperty: "Hi")
// Should return the aNewClass instance:
MyClass.currentClass()
Upvotes: 2
Views: 88
Reputation: 57114
You need to create a static property which you assign the already created member to:
class MyClass {
let myProperty: String
private static var instance : MyClass?
required init(myProperty: String) {
self.myProperty = myProperty
if MyClass.instance == nil {
MyClass.instance = self
}
}
class func currentClass() -> MyClass? {
return MyClass.instance
}
}
let aNewClass = MyClass(myProperty: "Hi")
This is somewhat similar to the singleton pattern, you can always retrieve the same object back from the class. You could alternatively remove the if
around the assignment causing the Class to always return the latest instance if that better suits your need.
Upvotes: 3