[英]In Swift 4, how can you get the string-representation of a data type stored in a variable of type 'Any'?
如果將值存儲在“任何”變量中,則獲取該值的數據類型的字符串表示的最簡單方法是什么?
例如,我正在調試具有此功能的代碼...
extension SomeClass : Mappable{
static func map(value:Any) -> SomeClass{
return Parse(value)
}
}
我試圖找出通過該函數傳遞的數據類型,但是如果我使用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)
}
}
我只是想將數據類型打印到調試窗口,而不要使用is
或as
進行測試,等等。這完全是出於記錄/調試的原因。
static func map(value:AnyObject) -> AnyClass{
return value.classForCoder
}
要么
static func map(value:Any) -> AnyClass{
return (value as AnyObject).classForCoder
}
在Swift 4中,您可以這樣實現:
static func map(value: Any) -> Any.Type {
return type(of: value)
}
好的,我知道了。 這是一個兩步過程。
你必須:
type(of:)
來獲取變量的類型(正如其他人所描述的) String(describing:)
獲得該類型的名稱(那是缺少的部分) 這是一個例子
let typeName = String(describing: type(of:value))
那就是我所追求的。 感謝您提供其他答案。 希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.