Swift 2.2循环通过字符串并得到char&指数

时间:2016-05-08 10:18:18

标签: string swift foreach swift2.2

我试图循环遍历String获取字符及其索引。听起来很简单..但我没有找到正确的语法。

以下是我的尝试:

let str = "testString"
for (index, char) in str.characters  {
    print(index)
    print(char)
}

for (index, char) in enumerate(str.characters)  {...}

2 个答案:

答案 0 :(得分:9)

let str = "testString"
for (index, element) in str.characters.enumerate() {
    print(index)
    print(element)
}

答案 1 :(得分:0)

Swift 4

let str = "Swift 4"
for (index, element) in str.enumerated() {
    print(index)
    print(element)
}