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?
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 .
In Swift, you can check for string and character equality with the "equal to" operator ( == ) and "not equal to" operator ( != ).
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.
main.swift var x = 25 if x is Int { print("The variable is an Int.") } else { print("The variable is not an Int.") }
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 } }
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