Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

know type of variable in Swift

Tags:

swift

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

like image 400
prabodhprakash Avatar asked Jan 13 '17 10:01

prabodhprakash


People also ask

What is type () in Swift?

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.

How do you check if a variable is a string in Swift?

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.

Is kind of in Swift?

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.

How do you check a string is Int in 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".


1 Answers

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
}
like image 174
dfrib Avatar answered Sep 19 '22 16:09

dfrib