Reputation: 465
I've been trying for the past few days learn how to insert data into every index in a 3-D array in swift. I am attempting to populate a 3-D array through a for-in loop. I know this example isn't correct because I'm not address each dimension in the array when I attempt to place in a value for the array, but I don't know how else to show what I mean:
var arr = [[[String]]]()
var brand = ["ford", "dodge", "toyota", "ford", "Nissan"]
var engine = ["2.0", "2.5", "3.4", "4.0", "5.0"]
var gas_mile = ["30", "25", "20", "15", "10"]
for index_1 in 1...brand.count{
arr[index_1] = brand[index_1]
for index_2 in 1...engine.count{
arr[index_1][index_2] = engine[index_2]
for index_3 in 1...gas_mile.count{
arr[index_1][index_2][index_3] = gas_mile[index_3]
}
}
}
I know you need to have an index for every dimension of the array ex:
arr[0][0][0] = gas_mile[0]
But I don't know how you would then add something to the first dimension of the array because the swift compiler is expecting a 2-D array ([[String]]) to be added, not a single value:
arr[0] = brand[0]
So I am confused how I would address the first or second dimension of the array in adding a value to it. I have little experience with swift, that's why I am asking on how you can address each individual dimension.
Upvotes: 0
Views: 49
Reputation: 59506
Here's a possible solution
struct Archive {
private var dict = [String:[String:Int]]()
func miles(byBrand brand: String, andEngine engine: String) -> Int? {
return dict[brand]?[engine]
}
mutating func set(miles: Int, forBrand brand: String, andEngine engine:String) {
var milesDict = dict[brand] ?? [String:Int]()
milesDict[engine] = miles
dict[brand] = milesDict
}
}
As you can see data is stored in a dictionary where the key is the brand name
and the value is another dictionary which has as key the engine and as value the miles.
Step 1: create your Archive
value
var archive = Archive()
Step 2: store data
archive.set(miles: 1, forBrand: "Ford", andEngine: "2.0")
archive.set(miles: 2, forBrand: "Ford", andEngine: "3.0")
archive.set(miles: 3, forBrand: "Ford", andEngine: "4.0")
archive.set(miles: 4, forBrand: "Ford", andEngine: "5.0")
archive.set(miles: 5, forBrand: "Audi", andEngine: "2.0")
Step 3: read data
archive.miles(byBrand: "Ford", andEngine: "2.0") // 1
archive.miles(byBrand: "Ford", andEngine: "3.0") // 2
archive.miles(byBrand: "Ford", andEngine: "4.0") // 3
archive.miles(byBrand: "Ford", andEngine: "5.0") // 4
archive.miles(byBrand: "Audi", andEngine: "3.0") // 5
Upvotes: 1