Reputation: 1475
I'm kinda new in Swift. I have some method that shows in few classes, in the same way, but only with different type. It looks like this:
class func loadDevice() -> Device
{
let object = super.loadFromDisk()
if object != nil
{
return object! as! Device
}
else
{
return Device.init()
}
}
class func loadUser() -> User
{
let object = super.loadFromDisk()
if object != nil
{
return object! as! User
}
else
{
return User.init()
}
}
As u can see, these 2 methods are the same. but i have to write them in every class but with different types.
Is it possible to write a "dynamic" static (or not static) method that do it in one place without writing this method in every class again and again?
Upvotes: 2
Views: 511
Reputation: 299345
The tool you want here is Self
.
class Thing {
class func loadFromDisk() -> Self? {
// Do something to load from disk, or return nil if you can't
// subclasses can override this if appropriate
return nil
}
class func create() -> Self {
// Try to load it from disk, but if we can't, create one
return loadFromDisk() ?? self.init()
}
required init() {}
}
class User: Thing {}
The init
method is marked required
to force every subclass to implement it somehow. It's ok if it's inherited, though. Remember, if you create custom designated initializers, then you lose all your inherited initializers since they're not valid anymore (they won't call your designated initializer, which you said was mandatory; that's what a "designated initializer" is). required
makes sure the initializer we rely on actually exists and hasn't been lost this way.
Upvotes: 3