Arjun321
Arjun321

Reputation: 99

Create Two dimensional Array of Arrays with two variable types in Swift

You can create a two dimensional array of one type of variable in swift with:

var array2D: [[String]] = [["hi", "bye"], ["hello", "goodbye"]]

I want to create a two dimensional array with the second variable a Float along the following lines:

var array2d2types = [[String,Float]] = [["height",1],["width",2]]

But this gives error: Cannot assign to immutable expression of type '[[Any]]'

How can I create an array of arrays each of which has a String and a Float?

Upvotes: 1

Views: 3143

Answers (2)

vacawama
vacawama

Reputation: 154691

You should use a custom struct if you want to store various types. This has the added benefit of allowing you to access those values with a meaningful name instead of just an index. Use an array of tuples and .map(Record.init) to initializes the array of structures.

struct Record {
    var string: String
    var float: Float
}

var records = [("height",  1), ("width", 2)].map(Record.init)

print(records[0].string)  // "height"
print(records[0].float)   // 1.0

Upvotes: 0

David Pasztor
David Pasztor

Reputation: 54775

Swift arrays are homogeneous, so you cannot store different typed elements in the same array. However, you can achieve your goals using an array of tuples instead of nested arrays.

let array: [(String,Float)] = [("height",1),("width",2)]

You can access the tuples using the normal subscript syntax

let firstTuple = array[0]

and the elements of the tuple using dot syntax

let height = firstTuple.0
let heightValue = firstTuple.1

However, you should use a custom struct or even better the built-in CGSize for storing height-width values.

Upvotes: 5

Related Questions