0

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;
    }
}

3 Answers 3

1

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

0

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 { }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.