copranos
copranos

Reputation: 7

Swift array basics

Gives an Index out of range eror. Is there a syntax error or logic ?

func generateGameBoard()->([Int]){
        var gboard =  [Int]();
        var i : Int = 0;
        for(i=0;i<8;i++){
            gboard[i]=1;
        }
        return gboard;
    }
}

Upvotes: 0

Views: 50

Answers (3)

Sahil
Sahil

Reputation: 9226

var gboard =  [Int](); // you are creating an empty array here.

you need to append value in array like

gboard.append(1) instead of   gboard[i]=1;

and c style for loop and ++ opeartor will not use in next versions of swift.

Upvotes: 1

Alex Zanfir
Alex Zanfir

Reputation: 573

You should also get ready for swift 3 and update the for loop part. It won't compile as it stand now in swift 3. You have to change it to: for i in 0..<8 { }

Upvotes: 0

Sandeep
Sandeep

Reputation: 21144

Dont you notice error in your code. You create an empty array and then ask index for 0 ..< 8 which is invalid. You should really use count to iterate over the contents.

   func generateGameBoard()->([Int]){
        var gboard =  [Int]();
        for i in 0 ..< gboard.count {
            gboard[i]=1;
        }
        return gboard;
    }

Upvotes: 1

Related Questions