知道Swift中的变量类型

pra*_*ash 12 swift

如何在Swift中识别变量的类型.例如,如果我写

struct RandomStruct....- 类型应该给我struct而不是RandomStruct

或者如果我写class RandomClass...的类型应该是class和不RandomClass.

我尝试过使用,Mirror.subjectType并且type(of:)两者都提供输出RandomStructRandomClass

dfr*_*fri 9

您接近使用Mirror:您可以查看反映在您的类型实例上的displayStyle属性(枚举类型Mirror.DisplayStyle)Mirror

struct Foo {}
class Bar {}

let foo = Foo()
let bar = Bar()

if let displayStyle = Mirror(reflecting: foo).displayStyle {
    print(displayStyle) // struct
}

if let displayStyle = Mirror(reflecting: bar).displayStyle {
    print(displayStyle) // class
}
Run Code Online (Sandbox Code Playgroud)

请注意,这.optional也是DisplayStyleenum的一个例子Mirror,所以一定要反思具体的(未包装的)类型:

struct Foo {}

let foo: Foo? = Foo()

if let displayStyle = Mirror(reflecting: foo as Any).displayStyle {
    // 'as Any' to suppress warnings ...
    print(displayStyle) // optional
}
Run Code Online (Sandbox Code Playgroud)