Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through a String Swift 2.0

I am trying to do a very simple piece of code in Swift playgrounds.

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

However, I always get an error on line 3.

'String' does not have a member named 'Generator'

Any ideas on why this doesn't work? Note: I am working in Xcode 7, with Swift 2.0 (Strings and Characters).

like image 790
Aaron Avatar asked Jun 10 '15 21:06

Aaron


2 Answers

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.

like image 122
ABakerSmith Avatar answered Sep 21 '22 17:09

ABakerSmith


String doesn't conform to SequenceType anymore. However you can access the characters property of it this way:

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

Note that the documentation hasn't been updated yet.

like image 39
lchamp Avatar answered Sep 20 '22 17:09

lchamp