I have a number of subclasses with a static var.
class A { }
class A1: A { static var intArray: [Int] = [] }
// …
class An: A { static var intArray: [Int] = [] }
I want to loop over the subclasses using something like
func test() {
let aTypes: [A.Type] = [A1.self, /* … */ An.self]
for aType in aTypes {
let nextSubclass = type(of: aType)
nextSubclass.intArray = [0] // Error: Type 'A.Type' has no member 'intArray'
}
}
I first thought about declaring static var intArray also in class A and to override it, but this is not allowed. I also tried to use a class var instead of a static var, but this is not allowed either.
Is there any way to achieve what I want?
While it is not possible to override
staticvars, it is possible to overrideclassvars.But first, consider making
Aa protocol.If
Amust be a class, you can useclassvars like this (this is quite a lot of boilerplate):Note that you should not use
type(of:)intest.aTypeis already the type you want: