Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tgnivekucn
Created January 4, 2023 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgnivekucn/256a78ea85e1c9187c4235ce96665c09 to your computer and use it in GitHub Desktop.
Save tgnivekucn/256a78ea85e1c9187c4235ce96665c09 to your computer and use it in GitHub Desktop.
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