Type Casting for Any & AnyObject in Swift
Written by Team Kodeco
Any
and AnyObject
are two special type aliases in Swift that allow you to cast any value to a specific type.
Any
is used to represent any type, including functions and optional types, whereas AnyObject
is used to represent any instance of a class type.
Here’s an example using Any
:
let mixedArray: [Any] = [1, "Hello", true, 2.0]
for item in mixedArray {
switch item {
case let x as Int:
print("Int: \(x)")
case let x as String:
print("String: \(x)")
case let x as Bool:
print("Bool: \(x)")
case let x as Double:
print("Double: \(x)")
default:
print("Unknown type")
}
}
In this example, an array mixedArray
is defined with elements of various types, including Int
, String
, Bool
, and Double
. The for
loop iterates over the elements of the array and uses a switch
statement to perform type casting and determine the type of each element.
Here’s an example using AnyObject
:
class Car {}
class Song {}
let objectsArray: [AnyObject] = [Car(), Car(), Song()]
for item in objectsArray {
if let car = item as? Car {
print("Car: \(car)")
} else if let song = item as? Song {
print("Song: \(song)")
} else {
print("Unknown type")
}
}
In this example, an array objectsArray
is defined with elements of class types, including Car
and Song
. The for
loop iterates over the elements of the array and uses as?
operator to perform type casting and determine the type of each element. If the type cast is successful, the appropriate message is printed.
Difference Between Any
and AnyObject
Any
is a type in Swift that can represent an instance of any type, including function types. It can be used to store heterogeneous collections of values.
AnyObject
is a type in Swift that can represent an instance of any class type. It can be used to store collections of class instances where the specific class type is unknown.
The main difference between Any
and AnyObject
is that Any
can represent any type, including value types and function types, while AnyObject
can only represent class types.