At this case, the container array should be of type [Any]
to let it contains ints and array of ints.
let arr1 = [1,2,3] // by default, it should be of type [Int]
let arr2:[Any] = [4,5,6,arr1]
print(arr2) // [4, 5, 6, [1, 2, 3]]
Note that Swift is strongly typed, by default, array must be an array of ints, -unlike Objective-C- array cannot contains mix of data types.
That's why you should Any type:
Any can represent an instance of any type at all, including function
types.
Note that:
Use Any and AnyObject only when you explicitly need the behavior and
capabilities they provide. It is always better to be specific about
the types you expect to work with in your code.
Accessing Elements:
By default, accessing elements from [Any]
array should be of type of Any
, for example:
let numberOne = arr2[0] // type of Any
let myArray = arr2[3] // type of Any
For getting the desired data type, you should cast it using as?
operator with optional binding, as follows:
if let oneInt = arr2[0] as? Int {
print("one is an Int and it equals to: \(oneInt)")
} else {
print("one is NOT ad Int")
}
// one is an Int and it equals to: 4
if let oneString = arr2[0] as? String {
print("one is an Int and it equals to: \(oneString)")
} else {
print("one is NOT ad Int")
}
// one is NOT ad Int
Remark: using as!
operator will cause the application to crash if the type does not matched.
let oneInt = arr2[0] as! Int // works fine
let oneString = arr2[0] as! String // CRASH!
For more information about as
operators you might want to check this Q&A and the Type Casting Documentation.