The following code shows an Class A which is the superclass of class B. The function has the return type 'Self'. The overridden method in class B courses an error (see the comment).
class A {
class func doSomething(param1: String) -> Self {
var entity = self()
// Some code goes here...
return entity
}
}
class B: A {
override class func doSomething(param1: String) -> Self {
var entity = super.doSomething(param1) as! B
// Some code goes here...
return entity // Error:'B' is not convertible to 'Self'
}
}
If I would have used instanceType in Objective-C it would work. So how can I get that working? Or is that not possible?
I want to have the method the return type of the current overriding class. A workaround would be to have an init-method which accepts the superclass type as parameter.
That brings up another question: an object casted to the current class isn't equal to self()?
So what is the difference between
var entity = someObject as! B
and
var entity = self() // Current class / file is B
EDIT:
class func objectCast<T: A>(obj: A) -> T {
return obj as! T
}
Returning objectCast(entity) instead of entity works.
class A {
class func doSomething(param1: String) -> Self {
var entity = self()
// Some code goes here...
return entity
}
}
class B: A {
override class func doSomething(param1: String) -> Self {
var entity = super.doSomething(param1) as! B
// Some code goes here...
return objectCast(entity) // No error.
}
}
So… Why does it need that trick, it seems like I've a problem with understanding the meaning of 'Self'. Can anyone answer the second part of my question about the difference?