Search code examples
iosarraysswiftmultidimensional-arrayfor-in-loop

Multidimensional Array Looping in cellForRowAtIndexPath Swift


I have a multidimensional array that I want to display the values of onto one UILabel in each respective cell.

My arrays look like this:

var arrayExample = [["beverages", "food", "suppliers"]["other stuff, "medicine"]]

I'm looping through these values in the cellForRowAtIndexPath in order for it to display on different cells (on a UILabel) the appropriate values:

if let onTheLabel: AnyObject = arrayOfContactsFound as? AnyObject {

                for var i = 0; i < objects!.count; i++ {


                    cell?.contactsUserHas.text = "\(onTheLabel[indexPath.row][i])" as! String

                    print("arrayOfContactsFound Printing! \(onTheLabel)")

                }

            }

When printing to the console I get:

arrayOfContactsFound Printing! (
        (
        beverages,
        "supply chain",
        pharmacuticals
    )
)

But on my label I get "beverages". That's it. How can I get the other 2 values (or X amount if there are more or less than 3 values)?

My for in loop is obviously not doing the trick. Assuming I can optimize/fix that to display all the values?

Thanks in advance.


Solution

  • In your loop you're setting the text of your label multiple times. Each time you set it it doesn't accumulate, it completely replaces the current text with the new text. You'll want something like this:

        // Remove the cast and the loop in your code example, and replace with this
        let items = arrayOfContactsFound[indexPath.row]
        let itemsString = items.joinWithSeparator(" ")
        cell?.contactsUserHas.text = itemsString
    

    Another thing to note is your cast doesn't quite make a lot of sense.

    var arrayExample = [["beverages", "food", "suppliers"]["other stuff, "medicine"]]
    

    So arrayExample is of type [[String]]. I'm assuming each cell in your table view represents one of the arrays of strings in your array. So each cell represents one [String]. So your items should be arrayExample[indexPath.row]. The cast to AnyObject doesn't make too much sense. If anything you'd be casting it to [[AnyObject]], but there's no reason to because the compiler should already know it's [[String]].