Nandin Borjigin
Nandin Borjigin

Reputation: 2154

How to get class type statically in swift

As the question may seem duplicated, I point out first that this is not asking for how to get a class type from an instance ( answer is using type(of:) ).

protocol Owner {
    static func name() -> String
}

extension Owner {
    static func name() -> String {
        return "\(self)"
    }
}

class Foo {
    var ownerName: String
    init(with owner: Owner.Type) {
        ownerName = owner.name()
    }
}

class Bar: Owner {
    var foo = Foo(with: Bar.self)
}

The code above simply works, but imagine that I want to rename the class Bar to BarBar then I need to change the initialization of foo to Foo(with: BarBar.self) manually. Is there any keyword that can be used instead of ClassName.self (e.g. Bar.self BarBar.self) to get the class type? Something like Self or Class (they don't compile actually)

Upvotes: 2

Views: 1066

Answers (1)

matt
matt

Reputation: 536028

My guess is that your whole question is a red herring and that type(of:self) is exactly what you want to say. In that case, the problem is merely that var foo is declared as an instance property. There are special rules for when you are allowed to say self while initializing an instance property (rightly, because self is exactly what does not yet exist during initialization). However, there are ways around that, as I have explained elsewhere; you can make this a computed instance property, or a lazy instance property, which is initialized by a function to be executed later, and then you are allowed to say type(of:self).

Upvotes: 3

Related Questions