indices(String) error

Swift programing Language Sample Code:

  1. for index in indices(greeting) {
  2.   print("\(greeting[index]) ")
  3. }


XCode 7 Beta Complier report Error:

cannot invoke 'indices' with an argument list of type '(String)'

'indices' is unavailable : access the 'indices' progperty on the collection

(Sorry about that—LCS has the right answer below. Strings are no longer a collection type in Swift 2, and the global indices function has become a property on collections like String.characters.)

Accepted Answer

That sample code is quite a collection of deprecated syntax, and somehow they missed it when they updated the book to Swift 2.0!

(from The Swift Programming Language > Language Guide > Strings and Characters > Accessing and Modifying a String)


The indices() function is gone too, and the print() function has changed to take over from println() and doesn't work so well in playgrounds when used incrementally, so the sample code would now probably be something like this:


let greeting = "Guten Tag"

var str = ""
for index in greeting.characters.indices {
    str = str + "\(greeting.characters[index]) "
}

print(str)
// prints "G u t e n   T a g "

I would write it like this:


let greeting = "Guten Tag"
var str = ""
  for char in greeting.characters {
  str = str + "\(char) "
}
print(str)

or like this:


let greeting = "Guten Tag" + "\n"
for char in greeting.characters {
    print(char, appendNewLine: false)
}


Of course, you have to click on the 'Show Debug Area' button in the top right of the playground window to see the printed results.

thanks for all.


indices(greeting.characters) is correct


another way:

for index in greeting.startIndex..<greeting.endIndex {

println(greeting[index])

}

indices(String) error
 
 
Q