In order to check if an object is of given type in Swift, you can use the type check operator is.
Given an example class Item, you can check if the object is of its type like that:
let item = Item()
if item is Item {
print("object is of Item subclass type")
} else {
print("object is not of Item subclass type")
}
The above code will print out “object is of Item subclass type”
Same applies to built-in data types in Swift. For example, if you’d like to check if given object is a String or Int:
let obj = 39
if obj is String {
print("Object is a String")
} else if obj is Int {
print("Object is an Int")
}
Check if given object is an array
Here is an example checking if the object is an array:
let obj = [1, 2, 3]
if obj is Array {
print("Object is an Array")
}
How to get the type of given object
If you’d like to get the type of given object, use the type(of:) method:
let item = Item()
let objectType = type(of: item)
print("Object type: \(objectType)")
The above code prints out Object type: Item
Related tutorials:
- How to convert String to Double or Float in Swift
- Floating point precision in Swift String
- How to pick a random element from an array in Swift