netdigger
netdigger

Reputation: 3789

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 {

}

Upvotes: 2

Views: 1159

Answers (1)

dfrib
dfrib

Reputation: 73186

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

Upvotes: 3

Related Questions