Reputation: 3927
How can I identify the type of variable in Swift. For e.g. if I write
struct RandomStruct....
- the type should give me struct
and not RandomStruct
or if I write class RandomClass...
the type should be class
and not RandomClass
.
I have tried using Mirror.subjectType
and type(of:)
both of which gives output as RandomStruct
and RandomClass
Upvotes: 12
Views: 206
Reputation: 73236
You were close with use of Mirror
: you can look at the displayStyle
property (of enum type Mirror.DisplayStyle
) of the Mirror
reflecting upon an instance of your type
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
}
Just note that .optional
is also a case of the DisplayStyle
enum of Mirror
, so be sure to reflect on concrete (unwrapped) types:
struct Foo {}
let foo: Foo? = Foo()
if let displayStyle = Mirror(reflecting: foo as Any).displayStyle {
// 'as Any' to suppress warnings ...
print(displayStyle) // optional
}
Upvotes: 10
Reputation: 96
You can check with this way;
if let randomClass = controlClass as? RandomClass {
/* Codes */
}
You can understand with this way, your variable which kind of class.
Upvotes: -3