4

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?

  • 1
    Perhaps you can use the `objcast()` trick? hack? from http://stackoverflow.com/a/27112385/1187415. (Returning `Self` seems to be difficult ...). In your case that would be `return objcast(entity)`. – Martin R Jun 01 '15 at 11:33

1 Answers1

0

Regarding your second question, the difference is that the first option will return B in any subclass and so subclasses won't return Self, while the second option will return an entity of Self in any subclass. If you mark class B as final the both approaches will work.