在Swift中创建包含不同类型的多维数组 [英] Creating multi-dimensional arrays containing different types in Swift
问题描述
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]
尝试从数组中读取"purchase_date"值,但出现错误无法将类型'(String,Date,Double,Int)'的值分配为'Date'",并且
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] {
...
}
给出类型为'String'的表达模式不能与类型为'(String,Date,Double,Int)'的值匹配"'
gives "Expression pattern of type 'String' cannot match values of type '(String, Date, Double, Int)'"
关于它为什么不采用我要在<array>[i][j]
中指定的元素的值/类型的任何线索,但似乎却试图采用<array>[i]
?我没看到什么?
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?
推荐答案
您已将元组值存储在数组中.因此,通过提供索引位置来访问元组的内容.
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
这篇关于在Swift中创建包含不同类型的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!