String Indexes in Swift 2

I decided to learn Swift, and I decided to start with Swift 2 right away.

So, here is a very simple example, similar to one from Apple’s own Swift e-book

let greeting = "Guten Tag" for index in indices(greeting) { print(greeting[index]) } 

I tried this on the Xcode 7 playground and I got the following error:

Cannot call "indexes" with argument list of type "(String)"

I also tried the same with Xcode 6 (this is Swift 1.2 AFAIK) and it worked as expected.

Now, my question is:

  • An error in Xcode 7, is it still a beta version, or?
  • Something that just doesn't work with Swift 2, and the e-book is not yet fully updated?

Also: if the answer is "2", how would you replace indices(String) in Swift 2?

+5
source share
3 answers

On the playground, if you go to the menu "View"> "Debug area"> "Show debug area", you will see a complete error in the console:

/var/folders/2q/1tmskxd92m94__097w5kgxbr0000gn/T/./lldb/94138/playground29.swift: 5: 14: error: "indexes" are not available: access to the "indexes" property in the collection for the index in indexes (greeting)

Also, String no longer matches SequenceType , but you can access their elements by calling characters .

So, the solution for Swift 2 should do it like this:

 let greeting = "Guten Tag" for index in greeting.characters.indices { print(greeting[index]) } 

Result:

G
at
t
e
n

T

g

Of course, I assume your example is just to check indices , but otherwise you could just do:

 for letter in greeting.characters { print(letter) } 
+8
source

Just to complete, I found a very simple way to get characters and substrings from strings (this is not my code, but I can’t remember where I got it from):

include this line extension in your project:

 extension String { subscript (i: Int) -> Character { return self[self.startIndex.advancedBy(i)] } subscript (i: Int) -> String { return String(self[i] as Character) } subscript (r: Range<Int>) -> String { return substringWithRange(Range(start: startIndex.advancedBy(r.startIndex), end: startIndex.advancedBy(r.endIndex))) } } 

this will allow you to do:

 print("myTest"[3]) //the result is "e" print("myTest"[1...3]) //the result is "yTe" 
+1
source

Here is the code you are looking for:

 var middleName :String? = "some thing" for index in (middleName?.characters.indices)! { // do some thing with index } 
-1
source

All Articles