Search code examples
swiftstringswift3segmentation-faultarc4random

Segmentation fault when trying to retrieve random letter from string


I have this function:

func getRandomLetter() -> String {
    let len = allPossibleLetters.characters.count
    let r = arc4random_uniform(UInt32(len))
    let index = allPossibleLetters.index (allPossibleLetters.startIndex, offsetBy: r)
    return String(allPossibleLetters[index])
}

However I keep getting the following error when trying to compile:

Command failed due to signal: Segmentation fault: 11

When I hardcode an integer into the offsetBy parameter, it works fine:

let index = allPossibleLetters.index (allPossibleLetters.startIndex, offsetBy: 11)
// returns a letter as expected

Any idea what causes this?


Solution

  • Seems like a problem with wrong type passed:

    let index = allPossibleLetters.index(allPossibleLetters.startIndex, offsetBy: Int(r))
    

    For those segmentation problems, if you click on that error it will take you to error details. Usually the very end of this log is most interesting. In your case it says:

    While type-checking expression at RangeText="allPossibleLetters.index(allPossibleLetters.startIndex, offsetBy: r)"