使用 Beta 3 时一切正常,现在我收到一个奇怪的错误,而且我不知道如何修复它。针对类似问题尝试了所有解决方案。
这是我的代码:
if !name.isEmpty {
var splitted: [String] = name.componentsSeparatedByString(" ")
for curPart in splitted {
if !curPart.isEmpty {
acronym += curPart.substringToIndex(1) //Error
}
}
if (acronym as NSString).length > 2 {
acronym = acronym.substringToIndex(2) //Error
}
}
两条标记线都给了我同样的错误:
Type 'String.Index' does not conform protocol 'IntegerLiteralConvertible'
有人可以帮助我吗?还是 Beta 4 被窃听了? 谢谢!
最佳答案
在 beta 4 中,Swift 的 String.Index 处理再次发生变化——当需要 String.Index
时,您现在不能提供 Int
。处理它的方法是使用 advance
方法创建您需要的 String.Index
:
if !name.isEmpty {
var splitted: [String] = name.componentsSeparatedByString(" ")
for curPart in splitted {
if !curPart.isEmpty {
acronym += curPart.substringToIndex(advance(curPart.startIndex, 1))
}
}
if countElements(acronym) > 2 {
acronym = acronym.substringToIndex(advance(acronym.startIndex, 2))
}
}
这一切都是基于确保正确处理 Unicode 字符串 - 因为不同的 Unicode 字符可以有不同的大小,纯整数索引会隐藏字符串不是随机访问的事实。
关于ios - 类型 'String.Index' 不符合协议(protocol) 'IntegerLiteralConvertible',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24880604/