Swift Array – With Elements of Different Types
In Swift, we can define an array that can store elements of any type. These are also called Heterogenous Collections.
To define an array that can store elements of any type, specify the type of array variable as [Any].
var arr: [Any]
We can also infer the array variable/literal to [Any] as shown in the following example.
var arr = [element_1, element_2,..] as [Any]
Now, let us go through some examples, where we define and initilize an Array with elements of different types.
In the following example, we will define an array
arr with elements of type Integer, String and Float.
var arr = [2, "ac", "abc", 5, 3.6] as [Any] print("Array : \(arr)")
Now, let us print the type of this array variable.
var arr: [Any] = [2, "ac", "abc", 5, 3.6] print(type(of: arr))
The array is of type Array<Any>.
In this Swift Tutorial, we learned how to define an initialize an Array with elements belonging to different types.