Swift 2中的字符串索引

6

我决定学习Swift编程语言,并且立刻开始学习Swift 2。

下面是一个非常基础的示例,与苹果官方Swift电子书中的示例类似。

let greeting = "Guten Tag"

for index in indices(greeting) {
    print(greeting[index])
}

我在Xcode 7的游乐场中尝试了此操作,结果收到以下错误提示:

无法使用类型为'(String)'的参数列表调用'indices'

我还使用了Swift 1.2所对应的Xcode 6进行了同样的操作,预期的结果得以实现。
那么,我的问题是:这是
  1. Xcode 7的一个错误,在beta版本发布后仍存在,还是
  2. 在Swift 2中已经不再适用,而电子书没有完全更新?
另外:如果答案是“2”,那么在Swift 2中该如何替代indices(String)
3个回答

10
在Playground中,如果你进入菜单视图(View) -> 调试区(Debug Area) -> 显示调试区(Show debug area),你就可以在控制台中看到完整的错误信息:
/var/folders/2q/1tmskxd92m94__097w5kgxbr0000gn/T/./lldb/94138/playground29.swift:5:14: error: 'indices' is unavailable: access the 'indices' property on the collection for index in indices(greeting)
此外,String不再符合SequenceType,但你可以通过调用characters来访问它们的元素。
因此,Swift 2的解决方案是这样的:
let greeting = "Guten Tag"

for index in greeting.characters.indices {
    print(greeting[index])
}

结果:

G
u
t
e
n

T
a
g

当然,我假设你的例子只是为了测试“indices”,但如果不是,你可以这样做:

for letter in greeting.characters {
    print(letter)
}

谢谢。是的,我只是在测试“indices”,并且已经知道了更简单的解决方案,因为之前在书中提到了“characters”。另外,你关于调试控制台的提示非常有帮助。 - mmgross
1
不客气。其实,我确实犹豫是否要添加最后一条评论,因为我相当确定您已经知道了。 :) 但是最终我还是添加了它,因为我认为它可以帮助未来的读者确保帖子的主题是“索引”,而不是实际访问字符。 - Eric Aya

1

为了完整起见,我找到了一种非常简单的方法来从字符串中获取字符和子字符串 (这不是我的代码,但我记不清我从哪里得到它了):

将此字符串扩展包含在您的项目中:

extension String {

    subscript (i: Int) -> Character {
        return self[self.startIndex.advancedBy(i)]
    }

    subscript (i: Int) -> String {
        return String(self[i] as Character)
    }

    subscript (r: Range<Int>) -> String {
        return substringWithRange(Range(start: startIndex.advancedBy(r.startIndex), end: startIndex.advancedBy(r.endIndex)))
    }
}

这将使您能够做到:

print("myTest"[3]) //the result is "e"
print("myTest"[1...3]) //the result is "yTe"

-1

这是你要找的代码:

var middleName :String? = "some thing"
for index in (middleName?.characters.indices)! {
// do some thing with index
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接