5

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.

2 Answers 2

8

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()
}
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent. Thank you. Is there a standard / rule for when to use protocol to share inheritance vs using a superclass?
Not really. But don't fight the type system. Many classes in the Apple frameworks which inherit from Objective-C are supposed to be subclassed. It depends on the environment.
4

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

2 Comments

Thank you for your answer. That works awesome for creating the array. But then having to unwrap each class with let battery = thing as? Battery.type kind of defeats the purpose of saving code as you would have to do that explicitly for each class.
See Vadian's answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.