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
Type casting is a way to check the type of an instance, or to treat that instance as a different superclass or subclass from somewhere else in its own class hierarchy. Type casting in Swift is implemented with the is and as operators.
Swift – Check if Variable/Object is String To check if a variable or object is a String, use is operator as shown in the following expression. where x is a variable/object. The above expression returns a boolean value: true if the variable is a String, or false if not a String.
isKind(of:) Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class. That is not Swift.
You might want to make isStringAnInt() a computed property extension String { var isInt: Bool { if let _ = Int(self) { return true } return false } } , then you can do "123".
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With