我有以下我评论过的代码:
func hash (s:String) -> Int {
var z = 19
let key = "abcdefghijk"
for var i = 0; i < s.characters.count; i++ {
let index = s.startIndex.advancedBy(i)
let char = s[index]
if let f = key.characters.indexOf(char) {
print(f) //This outputs the number I want to use in the next line, but as String.CharacterView.Index, not an Int
z = (z * f) //obviously this won't work
}
// So instead we try this:
z = z * s.startIndex.distanceTo(key.characters.indexOf(char)!))
// It works for the first few characters then I get "fatal error: can not increment endIndex" and a EXC_BAD_INSTRUCTION
}
return z
}
我正在努力使用 Swift String
来查找我想在某种哈希函数中用作 Int
的索引。如果不清楚:
用户输入一个字符串,该函数遍历每个字符,在 key
中找到该字符,然后获取该字符在 key
中的索引并将其乘以现有的 z
计数器。
我得到了我想要的结果,但类型错误,无法转换为 Int。谁知道怎么做?
谢谢
最佳答案
f = key.characters.indexOf(char)
是字符的索引
key
,因此您必须计算到 key
起始索引的距离,而不是 s
:
z = z * key.startIndex.distanceTo(key.characters.indexOf(char)!))
您可以将其移回您的 if-let
block :
if let f = key.characters.indexOf(char) {
z = z * key.startIndex.distanceTo(f)
}
您可能还想使用 overflow operator &*
if let f = key.characters.indexOf(char) {
z = z &* key.startIndex.distanceTo(f)
}
否则应用程序将崩溃,如果
乘法不适合 Int
。
一般情况下,Swift String
的索引只能使用
使用相同字符串(不考虑字符串长度),如下所示
示例演示:
let s1 = "abc"
let i1 = s1.characters.indexOf("b")!
print(i1) // 1
let s2 = "🇩🇪a🇩🇪b🇩🇪c"
print(s2.characters.count) // 6
let d2 = s2.startIndex.distanceTo(i1) // fatal error: can not increment endIndex
关于ios - 在 Swift 中作为整数的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556111/