如何在swift中管理字典数组的数组

时间:2017-10-11 12:31:48

标签: arrays xcode9 swift4

我有课程键,再次拥有一本字典并再次拥有数组。如何使用section key name在tableview中管理它将是 标题标题。请帮我。 提前致谢。

curriculam =         {
        pdf =             (
                            {
                id = 1;
                link = "google.com";
            },
                            {
                id = 2;
                link = "google.com";
            }
        );
        ppt =             (
                            {
                id = 1;
                link = "google.com";
            },
                            {
                id = 2;
                link = "google.com";
            }
        );
        test =             (
                            {
                id = 1;
                link = "google.com";
            },
                            {
                id = 2;
                link = "google.com";
            }
        );
        title = "lesson one";
        video =             (
                            {
                id = 1;
                link = "google.com";
            },
                            {
                id = 2;
                link = "google.com";
            }
        );
    };

1 个答案:

答案 0 :(得分:0)

您可以这样使用:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableview: UITableView!
    let curriculam = [
        "pdf": [["id":1,"link":"google1.com"], ["id":2,"link":"google2.com"], ["id":3,"link":"google3.com"]],
        "ppt": [["id":1,"link":"google1.com"], ["id":2,"link":"google2.com"]],
        "test": [["id":1,"link":"google1.com"], ["id":2,"link":"google2.com"]],
        "video": [["id":1,"link":"google1.com"], ["id":2,"link":"google2.com"]]
    ]

    var sections: [String] = []
    var items: [[[String: Any]]] = [[[:]]]

    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section]
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        var label: String = ""

        if let id = items[indexPath.section][indexPath.row]["id"] {
            label = "\(id)"
        }
        if let link = items[indexPath.section][indexPath.row]["link"] {
            label = "\(label)-\(link)"
        }

        cell.textLabel?.text = label
        return cell
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        tableview.delegate = self
        tableview.dataSource = self

        sections = curriculam.map { $0.key }
        items = curriculam.map { $0.value }
    }
}