manzarhaq
manzarhaq

Reputation: 55

Presenting a nested array in a TableViewController

Sorry if this is just a basic concept of Tables in Swift, but I'm quite new to Swift and have spent quite some time trying to figure this out with no luck.

I have an array named 'Data' which is structured like this:

var Data = [
["Alex","25","Male","258475"],
["Sean","29","Male","145737"],
["Grace","34","Female","295049"],
...
]

I'd like to present this in a TableViewController such that each cell contains the name, age, gender and an ID. Most examples that I've found use data structured in a different way:

var Data = [
["Alex","Sean","Grace"],
["25","29","34"],
["Male","Male","Female"],
...
]

Is there a way to use the data structure that I have and present it in rows of a table view? Or would I be better off restructuring my data? Thanks.

Upvotes: 1

Views: 336

Answers (2)

Joby Ingram-Dodd
Joby Ingram-Dodd

Reputation: 730

As I see it there are a couple of ways you can do this. You could create a struct which contains each person and have an array of those. Somthing like this.

struct Person {
   var name: String 
   var age: String
   var gender: String
   var id: String
}

Then store your data in an array

var data = [Person]

Then in your table cell you can set up to have a label for each of the items you want to display.

Or a down and dirty way you can get the info you want to show in the defualt cell text area is to concatonate the strings togther as s single string.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath)
    var cellText = ""
    let row = indexPath.row
    for x in data[row]{
        cellText = cellText + ", " + x
    }
    cell.textLabel?.text = cellText

    return cell
    }

In the above we find the array inside the data array which corresponds to the row number, then we loop through that array adding all the strings together to get 1 big string and then display that string in the table.

Here is a tutorial which gives a good overivew of table views which may help. https://www.codingexplorer.com/getting-started-uitableview-swift/

Upvotes: 2

vadian
vadian

Reputation: 285150

Nested multiple arrays as table view data source is the worst choice. Never use those.

The usual and recommended choice is a custom struct.

enum Gender {
    case male, female
}

struct Person {
    let name, id : String 
    let age : Int 
    let gender : Gender
}

let people = [Person(name:"Alex", id: "258475", age: 25, gender: .male),
              Person(name:"Sean", id: "145737", age: 29, gender: .male),
              Person(name:"Grace", id: "295049", age: 34, gender: .female)]

...

Upvotes: 1

Related Questions