NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

SOLVED: Calling object methods dynamically

Forums > Swift

So what I'm trying to figure out a way to do here is create a way to register action hooks in my application so that various modules can chime in at certain points while things are being executed and run their specified functions.

In WordPress, where I'm most accustomed to doing this, you can provide the add_action() function with the name of the hook and the function to call (or an array containing an object and a string with the method name). The system then uses the call_user_func($function_name)Link method for invoking the function dynamically.

I've figured out how to create objects dynamically from a string containing the class name (like so):

let aClass = NSClassFromString("MyClass") as! NSObject.Type
let anObject = aClass.init()

So in short I'm really looking for a similar type of method for invoking class methods.


Swift doesn't really do dynamism like that. This is what protocols are for. You would need to define a protocol with maybe a performAction method that you would then implement in objects conforming to your protocol. Then, in your main object, you would store an array of objects and call the performAction method on each one.

Something like this:

protocol Actionable {
    func performAction()

class MainThing {
    var actionableObjects = [Actionable]()

    func addActionObject(_ object: Actionable) {

    func runActions() {
        for obj in actionableObjects {

class Action1: Actionable {
    func performAction() {

class Action2: Actionable {
    func performAction() {

let thing = MainThing()


That's a pretty genius idea, actually! The Protocol will ensure that the function exists, so we don't have to go out of our way to fail gracefully or waste time querying everything. Thanks!


Hacking with Swift is sponsored by Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

Not logged in

Log in

Link copied to your pasteboard.