0

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

trungduc
  • 11,926
  • 4
  • 31
  • 55
lreddy
  • 449
  • 6
  • 19
  • what is your actual problem scenario? there is probably NO equivalent for swift. the swift approach is different. You may want to convert Obj-C code to swift. So tell something about your actual code base functionality. Did you [check this link](https://stackoverflow.com/questions/24167791/what-is-the-swift-equivalent-of-respondstoselector/35887129)? – Imrul Kayes May 21 '18 at 10:18
  • i have NSNumber * obj where i need to check the if ( [obj respondsToSelector:@selector(charValue)] ) { } same need to be converted to swift – lreddy May 21 '18 at 10:25

2 Answers2

2

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()

Amit Battan
  • 2,968
  • 2
  • 32
  • 68
2

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
Ankit Jayaswal
  • 5,549
  • 3
  • 16
  • 36