Iterate through a String Swift 2.0

As of Swift 2, String doesn’t conform to SequenceType. However, you can use the characters property on String. characters returns a String.CharacterView which conforms to SequenceType and so can be iterated through with a for loop:

let word = "Zebra"

for i in word.characters {
    print(i)
}

Alternatively, you could add an extension to String to make it conform to SequenceType:

extension String: SequenceType {}

// Now you can use String in for loop again.
for i in "Zebra" {
    print(i)
}

Although, I’m sure Apple had a reason for removing String‘s conformance to SequenceType and so the first option seems like the better choice. It’s interesting to explore what’s possible though.

Leave a Comment