Re: respondsToSelector in Swift


Quincey Morris
 

On Aug 7, 2017, at 09:51 , Gerriet M. Denkmann <g@...> wrote:

How to translate this into Swift

It’s not clear which part of that is giving you trouble, but I was able to do this in a playground (Swift 4, Xcode 9), and got the expected output:

class A: NSObject
{
@objc func transformedValue (value: AnyObject) -> AnyObject
{
if !value.responds (to: #selector (getter: AnyObject.doubleValue))
{
// log statement omitted
return NSNumber (value: 52)
}

return NSNumber (value: value.doubleValue)
}
}

let a = A ()

print (a.transformedValue (value: NSNumber (value: 10)))
print (a.transformedValue (value: "20" as NSString))
print (a.transformedValue (value: NSObject ()))

Note that Swift’s “AnyObject” has the same magic behavior as Obj-C’s id, that the compiler will let you call any known method on a receiver variable declared with the type.

Join cocoa@apple-dev.groups.io to automatically receive all group messages.