Reputation: 155
Thanks for taking the time to read my question. I have experience in php with multidimensional arrays but i am struggling to transfer my knowledge over to swift...
The plan is to create an array like this:
Category1 -- product1 --- description -- product2 --- description
Category2 -- product1 --- description -- product2 --- description
Category3 -- product1 --- description -- product2 --- description
And using 3 tableviews (1 on each viewcontroller) i would like to populate the info:
Tableview1 -- Category list. Tableview2 -- Product for selected category list. Tableview3 -- Description for selected.
I can populate 1 tableview using a simple array easily, but how would i:
1) Create the multidimensional array? 2) Count & populate each tableview? 3) Tie each child row to parent rows?
I really hope i am making sense and i am not looking for a free ride, just a helping hand as i am really enjoying learning the swift language!
Kind regards Rory
Upvotes: 1
Views: 1324
Reputation: 2547
Welcome to swift user1263909
How to create an array of strings
let stringArray = [String]()
How to create an array of strings with string literals
let categoryStringArray = ["Category1", "Catagory2", "Catagory3"]
How to create an array of string array's
let arrayOfArray = [[String]]()
how to create an array of string array literals
let a = [["Category1", "Catagory2", "Catagory3"],["product1", "product2", "product3"]]
accessing "Catagory3"
a[0][2]
However this all can get complicated fast. Why not use some structs?
struct Product {
var name:String
var description:String
var price:Double
//ect...
}
use struct to encapsulate data for easy use
let p1 = Product(name: "hat", description: "a hat", price: 2.00)
lets make an array of structs.
let arrOfProduct = [p1,Product(name: "tie", description: "a bow tie", price: 5.00)]
arrOfProduct now has two structs in it a tie and a hat. How to access hat's price
arrOfProduct[0].price
oh we could also have a struct for catagories, it can contain products as an array
struct Category {
var name:String
var products:[Product]
}
Lets create a Category for Clothes.
let clothes = Category(name: "Clothing", products: arrOfProduct)
lets create another catagory
let food = Category(name: "Food", products: [Product(name: "Candy", description: "Yummy Candy", price: 2.0)])
and finally we can have an array of Catagory
let arrC = [clothes,food]
now I can loop through all catagories in first table view to fill out the cell names
for c in arrC{
print(c.name)
}
when you switch to a new view controller pass it the correct array of products
let productsClicked = arrC[0].products
then on that new view controller loop the products
for p in productsClicked{
print(p.name)
}
if they click a product pass the product to the next view controller and so on. this will be much easier to maintain as you get new requirments.
Goodluck and welcome to swift. :D
Upvotes: 4