Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an object is a given type in Swift

I have an array that is made up of AnyObject. I want to iterate over it, and find all elements that are array instances.

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

like image 553
Encore PTL Avatar asked Jun 06 '14 23:06

Encore PTL


People also ask

Is type of class 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. For example, instances of a user-defined class named MyClass have the type MyClass .

How check string is value or not in Swift?

In Swift, you can check for string and character equality with the "equal to" operator ( == ) and "not equal to" operator ( != ).

What is .self in Swift?

In Swift, the self keyword refers to the object itself. It is used inside the class/structure to modify the properties of the object. You can assign initial values to properties in the init() method via self.

How do you check if a value is a number in Swift?

main.swift var x = 25 if x is Int { print("The variable is an Int.") } else { print("The variable is not an Int.") }


1 Answers

If you want to check against a specific type you can do the following:

if let stringArray = obj as? [String] {     // obj is a string array. Do something with stringArray } else {     // obj is not a string array } 

You can use "as!" and that will throw a runtime error if obj is not of type [String]

let stringArray = obj as! [String] 

You can also check one element at a time:

let items : [Any] = ["Hello", "World"] for obj in items {    if let str = obj as? String {       // obj is a String. Do something with str    }    else {       // obj is not a String    } } 
like image 71
drewag Avatar answered Sep 22 '22 19:09

drewag