Reputation: 2818
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.
Upvotes: 0
Views: 75
Reputation: 22487
What you need to do (as I said in my comment) is to both allocate the array to the size that you want, and to make it an array of Object?
rather than Object
(or Object!
- why do you do that?). Something like this, for a 2x2 array ...
var grid = [[Object?]](count:2, repeatedValue: [Object?](count:2, repeatedValue:nil))
Upvotes: 1
Reputation: 395
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]
}
}
Upvotes: 0