respondsToSelector in Swift


Gerriet M. Denkmann
 

How to translate this into Swift

- (id)transformedValue:(id)value
{
if ( ![value respondsToSelector: @selector(doubleValue) ] )
{
NSLog(@"%s Error value %@ %@",__FUNCTION__, [value class], value);
return @50;
};

NSNumber *input = (NSNumber *)value; // maybe NSString
double output = …
return @(output)
}

Gerriet.


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.


Gerriet M. Denkmann
 

On 8 Aug 2017, at 00:57, Quincey Morris <quinceymorris@rivergatesoftware.com> wrote:

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

How to translate this into Swift
It’s not clear which part of that is giving you trouble,
Mostly the #selector.
And also, I did not know about AnyObject.

This now seems to work:

final class SpeedValueTransformer: ValueTransformer
{
override class func transformedValueClass() -> AnyClass { return NSNumber.self }

override func transformedValue(_ value: Any?) -> Any?
{
let anyValue = value as AnyObject

if anyValue.responds(to: #selector (getter: AnyObject.doubleValue))
{
let optionalInput = anyValue.doubleValue

if let input = optionalInput
{
let output = input * 3 + 42
return output // NSNumber (value: output)
}
}

return 50 // error case
}
}

Thanks for your help!

Kind regards,

Gerriet.