如何在Swift中识别变量的类型.例如,如果我写
struct RandomStruct....
- 类型应该给我struct
而不是RandomStruct
或者如果我写class RandomClass...
的类型应该是class
和不RandomClass
.
我尝试过使用,Mirror.subjectType
并且type(of:)
两者都提供输出RandomStruct
和RandomClass
您接近使用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
也是DisplayStyle
enum的一个例子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)
归档时间: |
|
查看次数: |
175 次 |
最近记录: |