jgraft jgraft - 2 months ago 15
Swift Question

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.

Answer

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()
}