Iterate through String Swift 2.0

I am trying to make a very simple piece of code on Swift playgrounds.

var word = "Zebra" for i in word { print(i) } 

However, I always get an error message on line 3.

'String' has no member named 'Generator'

Any ideas on why this is not working? Note. I work in Xcode 7 with Swift 2.0 ( Strings and characters).

+44
swift swift2 xcode7 swift-playground
Jun 10 '15 at 21:26
source share
4 answers

As with Swift 2, String does not match SequenceType . However, you can use the characters property on String . characters returns a String.CharacterView that matches the SequenceType and therefore can be repeated using a for loop:

 let word = "Zebra" for i in word.characters { print(i) } 

Alternatively, you can add the extension to String to match 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 to remove the String matching SequenceType , and so the first option seems to be the best choice. It is interesting to study what is possible, though.

+77
Jun 10 '15 at
source share

String no longer matches SequenceType . However, you can access the characters property as follows:

 var word = "Zebra" for i in word.characters { print(i) } 

Please note that the documentation is not yet updated.

+9
Jun 10 '15 at 21:33
source share

Swift 3.0.1

Use the indices property of the characters property to access all indices individual characters in a string.

 let greeting = "Guten Tag!" for index in greeting.characters.indices { print("\(greeting[index]) ", terminator: "") } // Prints "G uten T ag ! " 

visit https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html

+2
Jan 18 '17 at 20:14
source share

Swift 4

Forin :

 let word = "Swift 4" for i in word { print(i) } 
Example

map :

 let word = "Swift 4" _ = word.map({ print($0) }) 

for each example:

 let word = "Swift 4" word.forEach({ print($0) }) 
+2
Jun 06 '17 at 9:22
source share



All Articles