Reputation: 910
I want to create a multi-dimensional array in Swift and following on from this post on creating multi-dimensional 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 seems ok but when I try to get the data back out with:
var subPurchaseDate: Date
subPurchaseDate = itemList[0][1]
to try to read the "purchase_date" value from the array I get the error "Cannot assign value of type '(String, Date, Double, Int)' to type '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's not taking the value/type of the element that I'm trying to specify in <array>[i][j]
but seems to be trying to take <array>[i]
? What am I not seeing?
Upvotes: 1
Views: 1307
Reputation: 9226
You have stored tuple value inside array. so, access the contents of a tuple by providing 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 using it's 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's 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
Upvotes: 4