lreddy
lreddy

Reputation: 479

Not able to find equivalent of respondsToSelector:@selector(charValue) in Swift 3

I have done lot of google to find the equivalent of respondsToSelector, still i could find any best solution. kindly suggest me for Any object in Swift3 or 4.

Objetive-C

[(id)object respondsToSelector:@selector(charValue)]

In Swift we have .method for AnyObject data type but for Any data type

Upvotes: 0

Views: 875

Answers (2)

Ankit Jayaswal
Ankit Jayaswal

Reputation: 5679

Reason: You can not write respondsToSelector for the swift-based function. There are 2 reasons.

1) In Objective-c, we do have charValue property in NSNumber class along with initWithChar. Whereas in swift we do not have any such properties in NSNumber class.

@property (readonly) char charValue;

- (NSNumber *)initWithChar:(char)value NS_DESIGNATED_INITIALIZER;

2) respondsToSelector only accepts Objective-C functions in argument.

Try with writing responds(to: #selector on NSNumber and you will found that it only accepts objective-c function and we don't have any such method in Swift NSNumber class.

let numb: NSNumber?
numb?.responds(to: #selector(@objc method))

Rather, You can use the swift string conversion of NSNumber, as:

let number: NSNumber?
let numberString = number?.stringValue ?? "" 
// Added default variable "" in case of string conversion becomes nil

Upvotes: 2

Amit Battan
Amit Battan

Reputation: 3018

you should first type cast then use

(object as? Type)?.charValue()

if your object is not of a type then it nil and never call the charValue()

Upvotes: 2

Related Questions