Can we have mixed data types in the same array?
Prerequisites
Please make sure you watch first the following prerequisite videos:
So can we store different types of data in the same array in Swift? There is a way, but don’t do it. Let’s discuss…
If we declare an array with the elements 1 and “Ray”, we will get an error. Because 1 is an integer, and “Ray” is a string. Total different data types. Does that mean that we can never ever have an array like this? Well, no, it doesn’t.
You see, when we declare an array full of integers, like 1, 2, 3, and 4, it’s the same as saying let numbers of type array of integers (notice that colon before the type declaration) be the array of 1, 2, 3, and 4. We can actually declare ourselves the type of the array first, and then assign the elements. The compiler will not get upset about that, but it is really not necessary, because Swift can do that for us. It’s called type inference.
And the same goes when we have an array of strings, or arrays of any other data type. We can choose to write the array type ourselves, or we can let the Swift compiler do it for us.
But, when we want to mix data types in the same array, Swift cannot infer the type anymore, it will get confused. It does not mean that we cannot mix data types, it simply means that we need to take care of declaring the type ourselves, and tell the compiler that we intentionally want mixed data type in the same array, by declaring the array to be an array of Any type. And this will work perfectly fine.
Fair warning, though. This is considered really bad programming. My advice to you: don’t do this!
And there you have it. There is a way to have mixed data type in the same array in Swift, by explicitly declaring the array to be an array of Any, which is a very special type of data, very rarely used. We cannot let the compiler infer the data type anymore, we need to take control and declare the type ourselves. But, even though this can be done, it is not recommended, and it is considered really bad programming.