简体   繁体   English

在Swift 4中,如何获取存储在“ Any”类型变量中的数据类型的字符串表示形式?

[英]In Swift 4, how can you get the string-representation of a data type stored in a variable of type 'Any'?

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. 我试图找出通过该函数传递的数据类型,但是如果我使用type(of :),我将不断获取“ Any”,而不是其中包含的值。

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. 我只是想将数据类型打印到调试窗口,而不要使用isas进行测试,等等。这完全是出于记录/调试的原因。

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

    return value.classForCoder

}

Or 要么

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

    return (value as AnyObject).classForCoder

}

In Swift 4 you can achieve that like this: 在Swift 4中,您可以这样实现:

static func map(value: Any) -> Any.Type {
    return type(of: value)
}

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) 使用type(of:)来获取变量的类型(正如其他人所描述的)
  2. Use String(describing:) to get the name of that type (that was the missing piece) 使用String(describing:)获得该类型的名称(那是缺少的部分)

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! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM