Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check the type of a variable in swift

Tags:

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.

like image 250
unixUser12 Avatar asked Jul 14 '14 21:07

unixUser12


People also ask

What is type () in Swift?

In Swift, there are two kinds of types: named types and compound types. A named type is a type that can be given a particular name when it's defined. Named types include classes, structures, enumerations, and protocols.

How do you check if a variable is a string 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.

How can I check if an object is of a given type in Swift?

“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.” Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.

How do you print a variable in Swift?

In Swift, you can print a variable or a constant to the screen using the print() function.


1 Answers

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.

like image 63
Bas Avatar answered Dec 08 '22 06:12

Bas