swiftselector

Swift 4 get Bool result from "perform" function call


I've got a function like this in Swift:

@objc func doSomeStuff(_ args: [String]) -> Bool {
    return true
}

And I have a selector name in String variable to execute. Here's my initial values:

let sel = Selector("doSomeStuff:")
let args = ["123123", "qweqweqwe"]

The problem is when I'm trying to receive the function calculation result like this:

let returnedValue = perform(sel, with: args)

Since that place I don't know how to get boolean value from returnedValue variable. Things I've already tried:

All of the above failed. So, how am I supposed handle this situation?


Solution

  • As you are using the ObjC runtime consider that you are dealing with objects. The ObjC signature is performSelector:withObject:

    In Swift you have to return a reference type NSNumber instance rather than value type Bool

    @objc func doSomeStuff(_ args: [String]) -> NSNumber  {
        return NSNumber(booleanLiteral: true)
    }
    

    and you have to dereference the pointer

    let result = perform(sel, with: args)
    let number = result!.takeUnretainedValue()