Swift: Methods like "type", "subclasses" and "override"

The following code shows class A, which is the superclass of class B. The function has a return type of "Self". An overridden method in class B indicates an error (see 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 were to use instanceType in Objective-C it would work. So how can I get this to work? Or is it impossible?

I want the method to return the type of the current override class. A workaround would be to have an init method that takes the type of the superclass as a parameter.


Another question arises: is the object assigned to the current class not equal to self ()?

So what's 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
}

      

An objectCast (entity) is returned, not an object.

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 do I need this trick, it looks like I have a problem understanding the meaning of "I". Can anyone answer the second part of my difference question?

+3


source to share


1 answer


Regarding your second question, the difference is that the first option will return B in any subclass and therefore the subclasses will not return Self, and the second option will return a Self object in any subclass. If you mark Class B as final, both approaches will work.



0


source







All Articles