简体   繁体   中英

How to relate two arrays in Swift

What is typically the process of creating arrays that relate to each other?

What I'm trying to do is to create a simple-shopping-list app where I will have two arrays, stores and items which will be displayed in a UITableView. The stores arrays will be displayed in the main tableView and the items array will be displayed in a detail tableView when an item from the stores array is tapped, but I'm not sure how this is typically done, I'm assuming I need some sort of two dimensional array (or one-to-many array) but I'm a little confused.

Here is the code I have which displays the stores array in the main tableView.

Store Class:

import Foundation

class Store{
    var storeName = ""
}

Item Class:

import Foundation

class Item : Object{
    var itemName: String = ""
    var price: Double = 0
}

Main ViewController:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var storesTable: UITableView!
    @IBOutlet weak var inputStoreName: UITextField!

    var itemList = [Item]() // I'm not sure how to use this array
    var storeList = [Store]()

    override func viewDidLoad() {
        super.viewDidLoad()
       storesTable.dataSource = self
       storesTable.delegate = self
    }
    @IBAction func addNewStore() {
        let store =  Store()
        store.storeName =  inputStoreName.text!
        storeList.append(store)
        storesTable.reloadData()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return storeList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =  tableView.dequeueReusableCell(withIdentifier: "myCustomCell")! as UITableViewCell
        let data  =  storeList[indexPath.row]
        cell.textLabel?.text = "\(data.storeName)"
        return cell
    }

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "detailTableView"{
      if let destination = segue.destination as? DetailTableViewController{

          let selectedStore = storeList[(storesTable.indexPathForSelectedRow?.row)!].storeName
        destination.messageFromMainController = selectedStore
      }
    }
   }

}

Actually you need to make changes in your model classes:

Store Class:

class Store{
    var storeName = ""
    var itemList : Array<Item>? = []
}

Now when you add the new store, you will add the items of this store with name.

 @IBAction func addNewStore() {
            let store =  Store()
            let item1 = Item()
            item1.itemName = "FirstStoreFirstItem"
            item1.price = "100"
            let item2 = Item()
            item2.itemName = "FirstStoreSecondtItem"
            item2.price = "200"
            store.storeName =  inputStoreName.text!
            store.itemList.append(item1)
            store.itemList.append(item2)
            storeList.append(store)
            storesTable.reloadData()
        }

Now when you select any store then you will get the details of items in that store as below

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "detailTableView"{
      if let destination = segue.destination as? DetailTableViewController{

          let selectedStore = storeList[(storesTable.indexPathForSelectedRow?.row)!]
         print(selectedStore.storeName)
         print(selectedStore.itemList[0].itemName)
         print(selectedStore.itemList[0].price)
        destination.messageFromMainController = selectedStore
      }
    }
   }

Add items in Store model

class Store{
var storeName = ""
var items:[Item]? = nil
}

Initiate Store object along with items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM