Creating multidimensional arrays containing different types in Swift

I want to create a multidimensional array in Swift and follow this post about creating multidimensional arrays, I came up with:

var itemList: [[(String, Date, Double, Int)]] = []

let itemID = purchases["itemID"] as! String
let purchase_date = purchases["purchase_date"] as! Date
let purchase_date_ms = purchases["purchase_date_ms"] as! Double
let quantity = purchases["quantity"] as! Int

itemList.append([(itemID, purchase_date, purchase_date_ms, quantity)])


This all looks fine, but when I try to get the data back:

var subPurchaseDate: Date
subPurchaseDate = itemList[0][1]


to try to read the value "purchase_date" from the array, I get the error "Can't assign a value of type" (String, Date, Double, Int) 'to enter "Date" and

switch itemList[iloop][0] {


gives "Expression pattern of type" String "cannot match values โ€‹โ€‹of type" (String, Date, Double, Int) "

Any clues as to why it doesn't take the value / type of the element I'm trying to point to <array>[i][j]

, but seems to be trying to take <array>[i]

? What can't I see?


source to share

1 answer

You have stored the value of the tuple inside the array. therefore, refer to the contents of the tuple by specifying the index position.

subPurchaseDate = itemList[0][1].0 // for string value
subPurchaseDate = itemList[0][1].1 // for date
subPurchaseDate = itemList[0][1].2 // for Double
subPurchaseDate = itemList[0][1].3 // for Int


You can also access it named value.

 var itemList: [[(stringValue: String, dateVal: Date, doubleValue: Double, intValue: Int)]] = []

// append elements in `itemList`
itemList.append([(stringValue: itemID, dateVal: purchase_date, doubleValue: purchase_date_ms, intValue: quantity)])

// access using it named value

subPurchaseDate = itemList[0][1].stringValue // for string value
subPurchaseDate = itemList[0][1].dateVal // for date
subPurchaseDate = itemList[0][1].doubleValue // for Double
subPurchaseDate = itemList[0][1].intValue // for Int




All Articles