UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

2      

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) {
        actionableObjects.append(object)
    }

    func runActions() {
        for obj in actionableObjects {
            obj.performAction()
        }
    }
}

class Action1: Actionable {
    func performAction() {
        print("Action1.\(#function)")
    }
}

class Action2: Actionable {
    func performAction() {
        print("Action2.\(#function)")
    }
}

let thing = MainThing()
thing.addActionObject(Action1())
thing.addActionObject(Action2())
thing.runActions()

4      

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!

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.