0

I wanted to instantiate a class and call a method of it dynamically.

class Test: NSObject {
    @objc func greet() {
        print("123")
    }
}

I am able to call the method given in string form using perform

let t = Test()
t.perform(Selector("greet"))

But I also want to init the test in a similar way.

let t = GetClass("Test").init()  // some method when called gives it's object
t.perform(Selector("greet"))

Here the Swift class will inherit from NSObject and have @obj added to its methods.


How to do the same using Objective-C methods but from Swift source code? For example,

let t = NSClassFromString("Test")
t.init() // ??
t.perform(Selector("greet"))

Edit: For the Objective-C, I got it working by following Call a method from a String in Swift. Need to include module name to get this working.

John Doe
  • 2,225
  • 6
  • 16
  • 44
  • Don't do it often. Thus swift will become `slow swift` – E.Coms Apr 02 '19 at 16:07
  • It is possible to do what you're trying to do here, but it will lead to very bad Swift. I don't agree that it will be slow Swift, but it will be very bad Swift and you will spend a lot of time fighting the compiler. What are you planning to do with this? As an exploration into the ObjC runtime, it's perhaps educational (though I'd probably just explore the ObjC runtime in ObjC), but there are much better Swift approaches to most things you'd want to do with this. – Rob Napier Apr 02 '19 at 16:17
  • I am trying to do FFI calls for language interop. I have a language written in Swift from which I want to access libraries written with Swift. – John Doe Apr 02 '19 at 16:28
  • 1
    I don't know what FFI means. But what you're describing won't work for arbitrary Swift. It only works for carefully constructed Swift that bridges to ObjC (and only then because it uses the ObjC runtime). Look at `@dynamicCallable` and `@dynamicMemberLookup`. These are the tools intended to help the kind of interop you're describing. – Rob Napier Apr 02 '19 at 18:56

0 Answers0