首页 > 解决方案 > 更新数组,聪明的方法?

问题描述

我正在使用struct 'xyz'包含变量。这些变量是arrayarr_InStruct”的一部分。arr_InStruct' '的副本dataSource在 TVC 中使用。

这是一个工作程序,但我对解决方案不满意。

缺点1:我需要知道indexPath变量在' arr_InStruct'中的确切位置()

缺点2:变得非常拥挤且难以阅读有什么建议可以array更智能地更新吗?

数据文件

import Foundation

struct xyz {
    //-> Variablen für Array
    //didSet updates the array in struct after value of variable was changed
    static var text0:String = "Entry 0" {didSet{arr_InStruct[0][0] = text0}}//push update 'arr_InStruct' bei Änderung
    static var text1:String = "Entry 1" {didSet{arr_InStruct[0][1] = text1}}//push update 'arr_InStruct' bei Änderung
    static var text2:String = "Entry 2" {didSet{arr_InStruct[0][2] = text2}}//push update 'arr_InStruct' bei Änderung
    static var text3:String = "Entry 3" {didSet{arr_InStruct[0][3] = text3}}//push update 'arr_InStruct' bei Änderung
    //<- Variablen für Array

    //disadvantage 1: I need to know the exact position (indexPath) of the variable within 'arr_InStruct'
    //disadvantage 2: becomes very crowded und unreadable
    //is there a smarter way to archive an array update?

    //2D Array
    //es wird gefüllt mit dem Inhalt der obigen Variablen
    static var arr_InStruct:[[String]] =
    [
        [
            text0,
            text1,
            text2,
            text3,
        ]
    ]//end arr_InStruct
}//end struct xyz

电视节目

import UIKit

class reloadTVTest: UITableViewController {

    //MARK: - >>> Arrays w data for TV
    let arr_Header = ["Section 0"] //1D Array 

    var arr_Data  = xyz.arr_InStruct { //2D Array in 'ArrayFile.swift' -> struct 'xyz'
        didSet{ //didSet will be called every time you change something in your array
            DispatchQueue.main.async {self.tableView.reloadData()} 
        }//end didSet
    }//end var
    //MARK: <<< Arrays w data for TV


    //MARK: - >>> Actions
    @IBAction func changePressed(_ sender: UIBarButtonItem) {
        print("""

            changePressed
            arr_Data in TVC:   \(arr_Data) <- Array in TVC before change
            xyz.arr_InStruct:  \(xyz.arr_InStruct) <- Array in struct before change

            """)

        xyz.text1 = "Entry changed "+randomString(length: 3) //change Variable in 'xyz'

        print("""

            xyz.text1:   '\(xyz.text1)' <- Variable changed in struct, didset called
            xyz.arr_InStruct: \(xyz.arr_InStruct) <- Array in struct changed by didSet
            arr_Data in TVC:  \(arr_Data)  <- but Array in TVC not changed
            """)

        arr_Data  = xyz.arr_InStruct //Array changed, didset called -> reloadData()

        print("""

            arr_Data in TVC was updated
            arr_Data in TVC:  \(arr_Data) <- now Array in TVC changed, didSet updated TV
            """)
    }
    //MARK: <<< Actions


    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // MARK: - Table view data source

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


    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UILabel()
        header.text = arr_Header[section]
        return header
    }


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


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellreloadTVTest", for: indexPath)
        let name = arr_Data[indexPath.section][indexPath.row]

        // Configure the cell...
        cell.textLabel?.text = name

        return cell
    }
}//end class reloadTVTest


extension reloadTVTest { //Swift 4.2, creating random String
    func randomString(length: Int) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
}//end extension reloadTVTest

结果: 使用按钮更改电视条目

标签: iosswift

解决方案


首先,有一些随你发出的struct XYZ

  1. static除非您在多个地方使用相同的对象,否则无需在其中制作所有内容。XYZ而是创建一个您想使用它的地方的单个实例。

  2. 与其将didSet观察者设置为 all text0, text1, text2 and text3arr_InStruct不如将其设置为计算属性。这种方式arr_InStruct将始终返回更新的值。

所以,XYZ就像,

struct XYZ {
    var text0 = "Entry 0"
    var text1 = "Entry 1"
    var text2 = "Entry 2"
    var text3 = "Entry 3"

    var arr_InStruct: [[String]] {
        return [[text0, text1, text2, text3]]
    }
}

接下来,在您的控制器reloadTVTest中,创建一个实例XYZ并将其用作dataSource您的tableView.

class reloadTVTest: UITableViewController {
    let arr_Header = ["Section 0"]
    var xyz = XYZ() {
        didSet {
            self.tableView.reloadData()
        }
    }

    //MARK: - >>> Actions
    @IBAction func changePressed(_ sender: UIBarButtonItem) {
        xyz.text1 = "Entry changed " + randomString(length: 3) //change Variable in 'xyz'
    }

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


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellreloadTVTest", for: indexPath)
        let name = xyz.arr_InStruct[indexPath.section][indexPath.row]
        cell.textLabel?.text = name
        return cell
    }

    //rest of the code....
}

推荐阅读