everlof everlof - 7 months ago 20
Swift Question

Any way to get the calling class on static functions in Swift?

The question is better explained in code:

class A {
class func thefunc() -> String {

/* Can I here know if thefunc was called using
A.thefunc() or
B.thefunc()?
*/

return "A" /* or "B"= */
}
}

class B: A {

}

Answer

You can use self in a static method to refer to the type (as compared to the instance for using self in an instance method)

class A {
    class func thefunc() -> A.Type {
        return self
    }
}

class B: A { }

let metaTypeA = A.thefunc() // A.Type
let metaTypeB = B.thefunc() // B.Type

Similarly, you can use runtime introspection, specifically the subjectType property of the Mirror representation of self.

Instance Variables

...

var subjectType: Any.Type

The static type of the subject being reflected.

From the swiftdoc.org reference of Mirror structure.

E.g.:

class A {
    class func thefunc() {
        print(Mirror(reflecting: self).subjectType)
    }
}

class B: A { }

A.thefunc() // A.Type
B.thefunc() // B.Type

Alternatively, if you needn't actually make use of the meta-type (just differ between the "static caller"), you could use the String representation of self.

class A {
    class func thefunc() -> String {
        return String(self)
    }
}

class B: A { }

print(A.thefunc()) // A
print(B.thefunc()) // B