How to name an instance of a struct the contents of a variable - Swift

限于喜欢 提交于 2020-05-17 06:10:12

问题


There is almost certainly a better way of doing this and I'd love to know but I can't phrase it in a question so essentially here is my problem:

I am creating an app that presents a list of items(In a table view) which have various bits of data that come along with the item(String Int Date ect). I've decided that the best way to store this data is in a struct because it allows me to store lost of different types of data as well as run processes on it.

The problem is that I want to have theoretically an infinite number of items in the list and so I need to make lost of instances of the Item struct without predetermining the names of each instance.

I would then store these instance names in an array so that they can be listed in the table view.

I'm completely stuck at this point I've spent hours looking and I just can't make sense of it I'm sure its stupidly easy because hundreds of apps must need to do this. I'm Open to anything thanks.

Currently, I have a struct:

struct Item() {
    var data1: String
    var data2: String // (But Should be Int)
    var data3: String

    func setDate() {
        // code
    }

    func returnDate() {
        // code
    }
}

and then in the view controller I have:

@IBAction func SubmitButton(_ sender: UIButton) {
    var textField1 = Item(data1: textField1.text!, data2: textFeild2.text!, data3: "Units")
    print(textField1.data1)
}

回答1:


I am not completely sure what your goal is but I guess the final goal is to have an array of your Item Objects, which then can be used to populate an UITableView??? Without setting up a name for this Instances?

The most easiest solution would be to create a array as a Class Property for storing all the Items which is empty like this:

var items : [Item] = []

And then in viewDidLoad(), you can call a function which populates the item array with all the available Items. This Item Array can then be used to populate the UITableView.

Second Part: You got this IBAction which creates a new Item. I guess this is supposed to add a new Item to the existing ones.

You can add this new Item to the existing Item Array by using

items.append(Item(<parameters>))

And don't forget to reload the UITableView to include the new data.

tableView.reloadData()


来源:https://stackoverflow.com/questions/61707272/how-to-name-an-instance-of-a-struct-the-contents-of-a-variable-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!