Self vs class type

if I declare this class:
open class Mario {
open func itsAMe() -> Mario {
return self
}
open func itsAMe() -> Self {
return self
}
}

Is the distinction that "Self" in this context means "the type of the most overloading class" instead of "the type of the declaring class"

3 Likes

Yes. For example, if you had a PaperMario subclass, the version that returns “Self” would return an instance of PaperMario, not just any Mario or random subclass thereof.

4 Likes

the dynamic type of self never changes, so the answer is yes-and-no, the static type of the returned instance is indeed the type of the declaring class, but all runtime dispatch will use the dynamic type of the instance, which is the “most overloading class”.

class Class 
{
    func staticself() -> Class 
    {
        return self
    }
    func dynamicself() -> Self 
    {
        return self
    }
    
    func declare() 
    {
        print("i am a base class")
    }
}
class Subclass:Class 
{
    override
    func declare() 
    {
        print("i am a subclass")
    }
}

let c1:Class    = .init(), 
    c2:Subclass = .init()

c1.staticself().declare() 
c1.dynamicself().declare()

c2.staticself().declare() 
c2.dynamicself().declare()

let c3:Class = c2 
c3.staticself().declare()
// i am a base class
// i am a base class
// i am a subclass
// i am a subclass
// i am a subclass
2 Likes
Terms of Service

Privacy Policy

Cookie Policy