Swift Type Checking and Casting (is / as Operators)
In this article, we will explain how to check and convert data types in Swift using the is and as operators.
Checking Types with is in Swift
In Swift, you can use the is operator to check the data type of a value.
For example, if you want to check whether the value stored in a variable of type Any is a String, you can write:
let value : Any = "test"
if value is String {
print("value is String")
} else {
print("value is not String")
}
When this is executed, since the value stored in value is a string, it prints value is String.
Now let's assign an integer to value and run the same code:
let value : Any = 1
if value is String {
print("value is String")
} else {
print("value is not String")
}
This time, since the value stored in value is an integer, it prints value is not String.
Converting Types with as in Swift
In Swift, you can use the as operator to convert data types.
The as? operator attempts the conversion and returns an Optional type.
If the conversion fails, it returns nil.
For example, let's cast the variable value using as? and check the resulting types:
let value : Any = "test"
let val1 = value as? String
print(type(of: val1))
let val2 = value as? Int
print(type(of: val2))
The output will be:
val1 is converted to an Optional String containing the value "test".
Since "test" cannot be converted to an integer, val2 becomes nil, and its type is Optional Int.
The as! operator works similarly to as?, but it forces the conversion to a non-Optional type.
let value : Any = "test"
let val1 = value as! String
print(type(of: val1))
Be careful: if the conversion fails, the program will crash.
You should only use as! when you are absolutely certain that the conversion will succeed and you want a non-Optional type.
let value : Any = "test"
let val2 = value as! Int
print(type(of: val2))
That's how you can check and convert data types in Swift using the is and as operators.