Reputation: 1514
I'm trying to convert some Objective-C to Swift code.
How can I convert this as I couldn't find any equivalent in swift.
((void (*)(id, SEL, id, id))objc_msgSend)(anObject, mySelector, anotherObject, lastObject)
Upvotes: 3
Views: 2198
Reputation: 5543
Swift 3.1
let handle : UnsafeMutableRawPointer! = dlopen("/usr/lib/libobjc.A.dylib", RTLD_NOW)
unsafeBitCast(dlsym(handle, "objc_msgSend"), to:(@convention(c)(Any?,Selector!,Any?,Any?)->Void).self)(anObject,#selector(mySelector),anotherObject,lastObject)
dlclose(handle)
You could alternatively use class_getMethodImplementation
unsafeBitCast(class_getMethodImplementation(type(of: anObject), #selector(mySelector)), to:(@convention(c)(Any?,Selector!,Any?,Any?)->Void).self)(anObject,#selector(mySelector), anotherObject,lastObject)
Upvotes: 6
Reputation: 42588
The Objective-C Runtime Reference has all the runtime functions listed.
Some of the functions have a Swift representation, some don't. For example, class_getName is available in Swift, but sel_getName is not.
The function objc_msgSend is not available to Swift.
After a quick search, I found this: Call a method from a String in Swift. Create an Objective C wrapper for objc_msgSend that will do the work for you. Not a great answer, but it seems to be the working solution for now.
Upvotes: 2