James James - 6 months ago 21
Swift Question

Swift: Which collection type to use for tracking status in 2 dimensional array

I'm a Swift newbie and I'm struggling with unfamiliar (to me) data structures. I'm trying to keep track of the status of the elements in a 2 dimensional array. Conceptually, I think it looks something like this:

x
|_group
| |_ item
| |_ item
| |_ item
|_group
|_ item
|_ item


My logic is that I want to create a dict (?) for the groups and within each element, I'll store another dict (?) with an integer key and a boolean value. When I initialize the collection type I want it to be 'empty'. So, an example:

If I set the 3rd item in the first group to true the entire collection looks something like this:

statusTracker[0:[2: true]]


If I then select the first element in the second group I get this:

statusTracker[0:[2: true],1:[0:true]]


...and setting the first element in the first group yields this:

statusTracker[0:[0:true, 2:true],1:[0:true]]


My question is twofold:
Is this a sensible collection type to achieve what I'm trying to do?
If so, how do I initialise this type of data structure without setting any values?

Answer

Declare your data structure as such:

var statusTracker = [Int: [Int:Bool]]()

For example:

 51> var statusTracker = [Int: [Int:Bool]]()
statusTracker: [Int : [Int : Bool]] = 0 key/value pairs
 52> statusTracker[0]=[0:true, 1:false, 2:false]
 53> statusTracker[1]=[0:false, 1:false]
 54> statusTracker
$R7: [Int : [Int : Bool]] = 2 key/value pairs {
  [0] = {
    key = 0
    value = 3 key/value pairs {
      [0] = {
        key = 2
        value = false
      }
      [1] = {
        key = 0
        value = true
      }
      [2] = {
        key = 1
        value = false
      }
    }
  }
  [1] = {
    key = 1
    value = 2 key/value pairs {
      [0] = {
        key = 0
        value = false
      }
      [1] = {
        key = 1
        value = false
      }
    }
  }
}

Whether or not this is the best way to represent your data is an entirely other issue.

Comments