问题
@IBAction func endTurn(sender: UIButton) {
let index: Int = Int (arc4random_uniform(UInt32(coins.count)))
var i = Int(arc4random_uniform((3)))
for i; i < 3; i++ {
coins[i].hidden = true
coins.removeAtIndex(i)
println(i)
}
}
I have 21 coins. It's array of buttons (@IBOutlet var coins: [UIButton]!). When i press "endTurn", the coins hidden. But when i have 3 coins or less, i get the fatal error (the line: coins[i].hidden = true). What i need do? Thanks...
回答1:
You are trying to access an index of the array that is out of bounds. So adding a check that the i
is in the range of the array should prevent a crash.
if(i < coins.length) {
coins[i].hidden = true
coins.removeAtIndex(i)
}
An array with 3 elements [0, 1, 2] goes from index 0-2 (the first index of an array is 0).
回答2:
Removing from an array while you iterate through it is a big no-no and probably not doing what you want it to.
var i = 0
var arr = ["1", "2", "3", "4", "5"]
for i; i < 3; i++ {
arr.removeAtIndex(i)
}
print(arr)
prints ["2", "4"] Because if you look at the code, you remove at index 0, so your array is now ["2", "3", "4"], then you increment i, and remove at index 1. Since the array shifted, index 1 is "3", and you are skipping over "2".
Use this information in conjunction with the other answers
回答3:
This loop:
for i; i < 3; i++ {
coins[i].hidden = true
coins.removeAtIndex(i) // <-- here
println(i)
}
On every iteration you delete a coin. So you can delete up to 3 coins in total, when arc4random_uniform
returns 0. When you have 3 (or fewer) coins left, you are bound to run into an index out of range problem.
回答4:
This is an Array Concurrent Modification
. And it's dangerous.
You should not modify the length
of an array while you are iterating it. You could end up in a scenario where you are accessing the element at an index that no longer exists.
Let Swift solve the problem for you with the removeRange
method. The following snippet should show you how to fix your code.
var animals = ["dog", "cat", "duck", "eagle", "cow"]
let from = 1
let to = 2
for i in from...to {
println(i) // will print `1` and `2`
}
animals.removeRange(from...to) // -> ["dog", "eagle", "cow"]
Hope this helps.
来源:https://stackoverflow.com/questions/31727256/swift-buttons-hidden-fatal-error-array-index-out-of-range