How to print class name in Swift


Gerriet M. Denkmann
 

This works (prints either null, NSString or NSNumber)

- (id)transformedValue:(id)value
{
NSLog(@"%s value %@ %@",__FUNCTION__, [value class], value);

}

But my Swift version:

override func transformedValue(_ value: Any?) -> Any?
{
print(“value \(String(describing: type(of: value))) \(String(describing:value))")

}

just prints:
value Optional<Any> Optional(33)

I do not want to know what the compiler things about value, I want to know what value is at run-time.

How can this be done?

Gerriet.


Dave Fernandes
 

My understanding is that an optional is just a type that wraps another type. So you need to unwrap the optional before calling String(describing: type(of: value))) to get the class name that you are interested in displaying. In other words, your print statement should be replaced with:

if let unwrappedValue = value
{
print(“value \(String(describing: type(of: unwrappedValue))) \(String(describing: unwrappedValue))")
}
else
{
print(“value nil”)
}

(Warning: code written in Mail.)

On Aug 7, 2017, at 12:25 PM, Gerriet M. Denkmann <g@mdenkmann.de> wrote:

This works (prints either null, NSString or NSNumber)

- (id)transformedValue:(id)value
{
NSLog(@"%s value %@ %@",__FUNCTION__, [value class], value);

}

But my Swift version:

override func transformedValue(_ value: Any?) -> Any?
{
print(“value \(String(describing: type(of: value))) \(String(describing:value))")

}

just prints:
value Optional<Any> Optional(33)

I do not want to know what the compiler things about value, I want to know what value is at run-time.

How can this be done?

Gerriet.