尝试从字符串中检索随机字母时出现分段错误
Segmentation fault when trying to retrieve random letter from string
我有这个功能:
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])
}
然而,我在尝试编译时不断收到以下错误:
Command failed due to signal: Segmentation fault: 11
当我将一个整数硬编码到 offsetBy 参数中时,它工作正常:
let index = allPossibleLetters.index (allPossibleLetters.startIndex, offsetBy: 11)
// returns a letter as expected
知道是什么原因造成的吗?
想通了。已更改
let r = arc4random_uniform(UInt32(len))
至
let r = Int(arc4random_uniform(UInt32(len)))
现在可以正常使用了。
似乎传递的类型有误:
let index = allPossibleLetters.index(allPossibleLetters.startIndex, offsetBy: Int(r))
对于那些分段问题,如果您单击该错误,它将带您到错误详细信息。通常这个日志的最后是最有趣的。
在你的情况下它说:
While type-checking expression at RangeText="allPossibleLetters.index(allPossibleLetters.startIndex,
offsetBy: r)"
我有这个功能:
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])
}
然而,我在尝试编译时不断收到以下错误:
Command failed due to signal: Segmentation fault: 11
当我将一个整数硬编码到 offsetBy 参数中时,它工作正常:
let index = allPossibleLetters.index (allPossibleLetters.startIndex, offsetBy: 11)
// returns a letter as expected
知道是什么原因造成的吗?
想通了。已更改
let r = arc4random_uniform(UInt32(len))
至
let r = Int(arc4random_uniform(UInt32(len)))
现在可以正常使用了。
似乎传递的类型有误:
let index = allPossibleLetters.index(allPossibleLetters.startIndex, offsetBy: Int(r))
对于那些分段问题,如果您单击该错误,它将带您到错误详细信息。通常这个日志的最后是最有趣的。 在你的情况下它说:
While type-checking expression at RangeText="allPossibleLetters.index(allPossibleLetters.startIndex, offsetBy: r)"