0

What is the easiest way to get the string-representation of a value's data type if that value is stored in an 'Any' variable?

For instance, I'm debugging code that has this...

extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        return Parse(value)

    }
}

I'm trying to figure out what data types are being passed through the function, but if I use type(of:) I keep getting 'Any' and not the value held in it.

extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        let nameOfType = ??? <-- This is what I'm trying to figure out
        log(nameOfType)

        return Parse(value)

    }
}

I simply want to print the data type to the debug window, not do testing with is or as, etc. It's strictly for logging/debugging reasons.

Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286

3 Answers3

1

Ok, I figured it out. It's a two-step process.

You have to:

  1. Use type(of:) to get the type of the variable (as others have described)
  2. Use String(describing:) to get the name of that type (that was the missing piece)

Here's an example...

let typeName = String(describing: type(of:value))

That's what I was after. Thanks for the other answers. Hope this helps!

Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286
0
static func map(value:AnyObject) -> AnyClass{

    return value.classForCoder

}

Or

static func map(value:Any) -> AnyClass{

    return (value as AnyObject).classForCoder

}
Santhosh R
  • 1,518
  • 2
  • 10
  • 14
  • This isn't what I'm after. Just like the other answer above, this changes the return type of the function. I'm trying to debug. I'm trying to log what's passed in. (I've updated the question to be more clear.) – Mark A. Donohoe Dec 08 '17 at 18:58
0

In Swift 4 you can achieve that like this:

static func map(value: Any) -> Any.Type {
    return type(of: value)
}
Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36
  • This changes the return type of the function. I'm trying to debug what's being passed to an existing function, not change the function. Make sense? (I've updated the question to be more clear.) – Mark A. Donohoe Dec 08 '17 at 18:58