Search code examples
iosarraysswiftlogicdidselectrowatindexpath

Array logic with indexpathforselectedrow


So I’m attempting to grasp nested array logic using indexpathforselectedrow! therefore, ill be using examples to explain my confusion.

my first thought: lets say I have

    var colors: array = [“red”,”orange”,”yellow”] 

in a table view.
If i got the indexpathforselectedrow of orange, what would that index value be? I assume that would be section = 0, row = 1, so [0][1]. would that be correct? or since this is a simple array, would the value just be one value? 1?

Secondly, if I have a more advanced array (please let me know if this array setup is correct)

 var morecolor: [[“green”,”blue”,”teal”][“light green”, “dark green”] 
[“light blue”, “dark blue”][“light teal”, “dark teal”]]

if I selected green (first array/ array 0) and wanted to segue to the light/dark green array, the second array (or first), how would i go about this?


Solution

  • An index path (NSIndexPath) consists of a section and a row. Both are integers, zero-based.

    The first section in your table is section 0, the second is 1, etc. Same for rows.

    You implement numberOfSections to tell how many sections you want, and numberOfRowsInSection to tell how many rows in each section (that method passes you the section number it needs the number of rows for).

    Typically you have a model that represents the data to be displayed, and you index into that model in cellForRowAtIndexPath.

    If you have a one-dimensional model, say a simple list of colors, you might have just one section, and as many rows as colors in your model. The color corresponding to any row would be something like:

        model.colors[indexPath.row]
    

    You can ignore section here because you know it's always zero (you only have 1 section).

    If you have a two-dimensional model, say a set of themes each of which consists of several colors, you would have as many sections as themes, and rows as colors in each theme. The theme and color corresponding to any row would be something like:

        model.theme[indexPath.section].colors[indexPath.row]
    

    Many table view methods use index paths, so it's useful to know how they work.