A Tyshka A Tyshka - 5 months ago 6
Swift Question

Swift Enumerate out of Range

I'm working on making a tile-based adventure game and I'm trying to generate tile maps. I put together some code that removes inland tiles from the list of possible new tile locations. I have a method that detects if a tile is coastal.

for (index, tile) in landTiles.enumerate() {
let coastal = isCoastal(tile.y, x: tile.x)
if coastal {
} else {

When I run this code I'm getting an
error: index out of range
message. I believe this is because the indexes are getting confused when I delete an item from landTiles. How could I fix this?


You are removing elements from an array while you enumerate it. And this is an anti-pattern.

What should you do instead?

The Tile class

First of all, the Tile class should have a isCoastal computed property. Something like this

class Tile {
    let x: Int
    let y: Int
    var isCoastal: Bool { /* your logic goes here */ }

    init(x:Int, y:Int) {
        self.x = x
        self.y = y


Now given an array of Tile(s)

var landTiles: [Tile] = ...

you can extract the ones having isCoastal true

let coastTiles = landTiles.filter { $0.isCoastal }

and overwrite the original array with the ones having isCoastal false.

landTiles = landTiles.filter { !$0.isCoastal }

That's it.