2

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.

Skoua
  • 3,373
  • 3
  • 38
  • 51
  • What happens if you change `in answer! as String` to: `in answer as? String`...? And what is `answer` set to? – nhgrif Nov 26 '14 at 00:27
  • If I do this I get a compiler error: `String? does not have a member named Generator` answer value is `Tetris` – Skoua Nov 26 '14 at 22:34
  • Just tried to make answer a `String` instead of `AnyObject`, no luck. – Skoua Nov 26 '14 at 22:48
  • 2
    Can you actually post some of the code in which you're using this, and the exact error message? You're asking for an awful lot of guesswork and I'm fresh out of tea leaves. – nhgrif Nov 26 '14 at 22:56

1 Answers1

1

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))
Matt Gibson
  • 37,886
  • 9
  • 99
  • 128
  • @Skoua Yeah; the bad instruction exception is usually a sign that an assertion has failed inside Apple's libraries. The assertion failure code deliberately throws a bad instruction onto the CPU to make sure the program halts. – Matt Gibson Nov 27 '14 at 07:58