So I'm trying to parse a String and fill an Array with each characters casted as String and I'm also removing white spaces.
Here's a part of the code:
class KeyboardView: UIView {
var answer: AnyObject?
var keyboardLetters = [String]()
override func willMoveToSuperview(newSuperview: UIView?) {
for letter in answer! as String {
if letter != " " {
keyboardLetters.append(String(letter).lowercaseString)
}
}
}
}
When I remove the for loop, the error disappears, and it happens only on iPhone 4s and iPhone 5, 5s and above are fine.
Any idea on how to fix this or getting more info about the error?
Thanks.
EDIT
Oh and I tested this in Xcode 6.1, Xcode 6.1.1 and Xcode 6.2 beta. Same thing everywhere.
EDIT2
Here's a bigger part of the code, I just noticed that if I remove everything after the line starting with userAnswer, the error goes away.
for letter in answer! as String {
if letter != " " {
keyboardLetters.append(String(letter).lowercaseString)
}
}
userAnswer = [Int](count: keyboardLetters.count, repeatedValue: -1)
while keyboardLetters.count < 21 {
let randomNumber = Int(arc4random()) % 25
let randomLetter = String(alphabet[randomNumber])
keyboardLetters.append(randomLetter)
}
keyboardLetters = shuffle(keyboardLetters)
Pardon my Swift, it's my first app.
Your problem is almost certain to be the arc4random()
call. It returns an unsigned 32-bit integer. On a 32-bit platform, Swift's Int
is 32-bit signed, so about half the time, your randomNumber
will end up being negative. Negative numbers don't make for good array indices.
You should be using arc4random_uniform()
anyway, as that will avoid the bias you'll get by taking the modulo yourself. As a bonus, that should fix the negative number problem, too:
let randomNumber = Int(arc4random_uniform(25))