unixUser12
unixUser12

Reputation: 83

how to check the type of a variable in swift

I want to know what the type is of a AnyObject variable that i initialise later. For example:

var test: AnyObject

test = 12.2

I cant figure out how to do this.

Upvotes: 8

Views: 5343

Answers (1)

Bas
Bas

Reputation: 4551

You can do this with the is operator. Example code:

var test: AnyObject

test = 12.2

if test is Double {
    println("Double type")
} else if test is Int {
    println("Int type")
} else if test is Float {
    println("Float type")
} else {
    println("Unkown type")
}

According to Apple docs:

Checking Type

Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.

Upvotes: 12

Related Questions