Search code examples
swiftdynamic-arrays

How to get value from array of arrays


I have array of arrays grid in my code. what I want to do is checking if there is a object at x, y let object = grid[x][y] if object is not nil I edit it else I assign a new object to it grid[x][y] = newObject().

if let object = grid[x][y] {
   object.property = newValue
} else {
   grid[x][y] = newObject()
}

but I get fatal error: Array index out of range in the line if let object = grid[x][y] {

what is the best way to do that? Thanks in advance.


Solution

  • Firstly, if you want to modify your grid object down the road, you can't define it with let. You must use var.

    It looks like you're trying to use optional binding (if let x = Optional(y) { ... }) with array subscripting (array[x]). This won't work, as an array subscript doesn't return an optional. It'll instead return a valid object or throw an exception. You could try this:

    if grid.count > x {
      if grid[x].count > y {
        object = grid[x][y]
      }
    }