An array of arrays with Inner array made up of two elements of different types

I am trying to create an array of arrays where the inner arrays have just two elements and are of different type. I have tried var myArray: [[Date, Float]] = but Xcode indicates that I have made two declarations on one line. If I do this: var myArray = [[Date(), 343.2]] to initialize the array Xcode does not balk. Can I create the array using some variation on my initial try i.e. var myArray: [[Date, Float]] = ?

Does it need to be an inner array, or would a tuple work?

var x: [(Date, Float)]

Or perhaps a custom struct?

Or maybe even just a dictionary, [Date: Float] or suchlike?

2 Likes

The reason you get an error when you try [[Date, Float]] is because Arrays can only contain one type, but you are trying to put two into it. When you declare an Array explicitly with multiple types like you did with [[Date(), 343.2]] what you are actually getting is [[Any]], which is probably not what you want.

If you want a data structure to hold 2 different types of values you will need to use Tuples or make your own Struct (or Class) like @Nevin suggested, which will let you give better names to the type and properties.

1 Like

I will try using a struct.
Thank you for helping me have a better understanding of Swift.