[英]In Swift 4, how can you get the string-representation of a data type stored in a variable of type 'Any'?
[英]How can I get a “Any?” variable's real type in Swift
我从Mirror.children获取属性列表,它返回(标签:String ?,值:Any)。 我如何获取每个值的实型。
var a: Int = 1
var b: Int? = nil
var c: Any?
c = a
getType(c) -> "Int"
c = b
getType(c) -> "Optional<Int>"
您可以看一下c.dynamicType
。
元类型类型是指任何类型的类型,包括类类型,结构类型,枚举类型和协议类型。
类,结构或枚举类型的元类型是该类型的名称,后跟.Type。 协议类型的元类型(不是在运行时符合协议的具体类型)是该协议的名称,后跟.Protocol。 例如,类类型SomeClass的元类型是SomeClass.Type,协议SomeProtocol的元类型是SomeProtocol.Protocol。
您可以使用后缀自我表达式来访问类型作为值。 例如,SomeClass.self返回自身的SomeClass,而不是SomeClass的实例。 而且SomeProtocol.self返回自身的SomeProtocol,而不是在运行时符合SomeProtocol的类型的实例。 可以将dynamicType表达式与类型的实例一起使用,以访问该实例的动态运行时类型作为值,如以下示例所示:
class SomeBaseClass {
class func printClassName() {
print("SomeBaseClass")
}
}
class SomeSubClass: SomeBaseClass {
override class func printClassName() {
print("SomeSubClass")
}
}
let someInstance: SomeBaseClass = SomeSubClass()
// The compile-time type of someInstance is SomeBaseClass,
// and the runtime type of someInstance is SomeBaseClass
someInstance.dynamicType.printClassName()
// prints "SomeSubClass
使用标识运算符(===和!==)来测试实例的运行时类型是否与其编译时类型相同。
if someInstance.dynamicType === someInstance.self {
print("The dynamic type of someInstance is SomeBaseCass")
} else {
print("The dynamic type of someInstance isn't SomeBaseClass")
}
// prints "The dynamic type of someInstance isn't SomeBaseClass"
使用初始化程序表达式根据该类型的元类型值构造该类型的实例。 对于类实例,被调用的初始化器必须标记为required关键字,或者整个类标记为final关键字。
class AnotherSubClass: SomeBaseClass {
let string: String
required init(string: String) {
self.string = string
}
override class func printClassName() {
print("AnotherSubClass")
}
}
let metatype: AnotherSubClass.Type = AnotherSubClass.self
let anotherInstance = metatype.init(string: "some string")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.