Swift - Array Data Types


If you mix the elements of an array with different types, like the following, the compiler will generate an error:

var nameArray = ["iOS", "Android", 5 ]

The compiler will try to infer the data type when the array is being initialized.

The third element's type is not compatible with the rest of the elements and the compilation fails.

To define type for your arrays to contain items of the same type, and you can do so explicitly like this:

var nameArray:Array<String> = ["iOS", "Android", "Windows"]

There is a shorthand syntax for arrays whereby you can simply specify the type using the following form: [ DataType ], like this:

var nameArray :[String]  = ["iOS", "Android", "Windows"]

The [String] forces the compiler to check the types of elements inside the array and flag an error when it detects elements of different types.

The following example shows an array of integers:

var numbers:[Int] = [0,1,2,3,4,5,6,7,8,9]

Related Topic