jgraft
jgraft

Reputation: 938

Swift - create an array of classes

I saw this question, but what I want is to create an array of the actual classes so that I can call a class function on each of them.

Example:

let syncClasses:[Any] = [Battery, Tank, Gas]
for object in syncClasses {
  object.someClassMethod()
}

I tried using [Any] as a type for the array but that threw:

Expected member name or constructor call after type name

All of the classes inherit from the same Object class so I can hack it by doing:

let syncClasses:[Object] = [Battery(), Tank()]

but then I have to make the function I want to call a method instead of a class function and that's not as clean as I would like.

Upvotes: 5

Views: 8381

Answers (2)

vadian
vadian

Reputation: 285039

A swifty way is to use a protocol:

protocol Drainable {
  static func drain()
}

class Battery : Drainable {
  static func drain() { print("battery drained") }
}

class Tank  : Drainable {
  static func drain() { print("tank drained") }
}

class Gas  : Drainable {
  static func drain() { print("gas drained") }
}

let syncClasses : [Drainable.Type] = [Battery.self, Tank.self, Gas.self]

for object in syncClasses {
  object.drain()
}

Upvotes: 8

Lance
Lance

Reputation: 9012

You can use .self to get the class type off the class symbol like this:

class Battery {
    class func test() {}
}

class Tank {}
class Gas {}

let array: [AnyClass] = [Battery.self, Tank.self, Gas.self]

for thing in array {
    if let battery = thing as? Battery.Type {
        Battery.test()
    }
}

Upvotes: 4

Related Questions