Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift messages dispatch
import Foundation
class CustomClass: NSObject {
@objc func getValue(_ arg: Int) {
print("val is: 100")
}
@objc func getValue2() {
print("val is: 2")
}
}
private func executeAction(className: String, methodName: String, arg: Any?) {
let cla: AnyClass? = NSClassFromString(className)
if let cla = cla as? NSObject.Type {
let selector: Selector = Selector(methodName)
let instance = cla.init()
if (instance.responds(to: selector)) {
if let arg = arg {
instance.perform(selector, with: arg)
} else {
instance.perform(selector)
}
} else {
print("method not found")
}
} else {
print("class not found")
}
}
executeAction(className: "YourProjectName.CustomClass", methodName: "getValue:", arg: 100)
executeAction(className: "YourProjectName.CustomClass", methodName: "getValue2", arg: nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment