Michael Michael - 6 months ago 96
Swift Question

Swift 2.2 loop through string and get char & index

I'm trying to loop through a String get get the characters as well as their index. Sounds easy.. but I'm not finding the correct syntax for doing that.

Here is what I was trying:

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


or

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

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