Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift2 enumerate function on a dictionary item

I am following a tutorial from Swift1 where they enumerate through an array using the 'enumerate' function. Since Swift2 they changed the way this is done, and I can no longer get this working for a certain array of type 'AnyObject'.

Here is the code that I am having trouble with:

init(filename: String) {
    if let dictionary = Dictionary<String, AnyObject>.loadJSONFromBundle(filename) {
        if let tilesArray: AnyObject = dictionary["tiles"] {
            for(row, rowArray) in enumerate(tilesArray as! [[Int]]) {
                let tileRow = NumRows - row - 1

                for (column, value) in rowArray.enumerate() {
                    if value == 1 {
                        tiles[column, tileRow] = Tile()
                    }
                }
            }
        }
    }
}

I have fixed this line by changing it from

for (column, value) in enumerate(rowArray) {

to

for (column, value) in rowArray.enumerate() {

And this worked fine

The line I am having troubles with is this one:

for(row, rowArray) in enumerate(tilesArray as! [[Int]]) {

The tilesArray doesn't have the function enumerate() for type AnyObject, and I'm not sure how to get around this. I am still very new to this language so this is sort of a road block at the moment.

Any help would be awesome! If there is any code missing I will happily provide it.

like image 847
Kyle Jensen Avatar asked Jan 31 '26 02:01

Kyle Jensen


1 Answers

You still need the cast to [[Int]]:

for (row, rowArray) in (tilesArray as! [[Int]]).enumerate() {

Or even better, you can use:

if let tilesArray = dictionary["tiles"] as? [[Int]] {
like image 73
jtbandes Avatar answered Feb 01 '26 17:02

jtbandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!