Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Unmanaged<AnyObject>! to Bool in Swift

Tags:

ios

swift

I am trying to get the result of a method of an existing Objective C class, called using performSelector

let result = controlDelegate.performSelector("methodThatReturnsBOOL") as? Bool

I need to cast this result to Bool type of Swift.

The code mentioned above, gives a warning

"Cast from 'Unmanaged!' to unrelated type 'Bool' always fails"

and the result is always "false", even when the method returns YES.

Any suggestions for converting the result to Bool ?

Signature for methodThatReturnsBOOL

- (BOOL)methodThatReturnsBOOL
{
    return YES;
}
like image 510
UditS Avatar asked Oct 08 '15 13:10

UditS


2 Answers

It's been a long time since this has remained unanswered so I'm adding what I have learned along the way.

To convert a BOOL value returned by an Objective C method you can simply cast it using,

if let result = controlDelegate.performSelector("methodThatReturnsBOOL") {
    print("true")
} else {
    print("false")
}

Here you can also assign the value true/false to a Swift Bool, if required.

Note : I tried casting Unmanaged<AnyObject> directly to Bool using takeRetainedValue() as suggested by many answers on SO, but that doesn't seem to work in this scenario.

like image 155
UditS Avatar answered Sep 28 '22 04:09

UditS


This is the solution in Swift 3, as the methods are a bit different. This method also checks if Objective-C object responds to selector, to avoid crashing.

import ObjectiveC

let selector = NSSelectorFromString("methodThatReturnsBOOL")

guard controlDelegate.responds(to: selector) else {
    return
}

if let result = controlDelegate.perform(selector) {
    print("true")
}
else {
    print("false")
}
like image 40
Legoless Avatar answered Sep 28 '22 04:09

Legoless