Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2.0 : 'enumerate' is unavailable: call the 'enumerate()' method on the sequence

Tags:

swift

swift2

Just downloaded Xcode 7 Beta, and this error appeared on enumerate keyword.

for (index, string) in enumerate(mySwiftStringArray)
{

}

Can anyone help me overcome this ?

Also, seems like count() is no longer working for counting length of String.

let stringLength = count(myString)

On above line, compiler says :

'count' is unavailable: access the 'count' property on the collection.

Has Apple has released any programming guide for Swift 2.0 ?

like image 889
itsji10dra Avatar asked Jun 09 '15 11:06

itsji10dra


2 Answers

Many global functions have been replaced by protocol extension methods, a new feature of Swift 2, so enumerate() is now an extension method for SequenceType:

extension SequenceType {
    func enumerate() -> EnumerateSequence<Self>
}

and used as

let mySwiftStringArray = [ "foo", "bar" ]
for (index, string) in mySwiftStringArray.enumerate() {
   print(string) 
}

And String does no longer conform to SequenceType, you have to use the characters property to get the collection of Unicode characters. Also, count() is a protocol extension method of CollectionType instead of a global function:

let myString = "foo"
let stringLength = myString.characters.count
print(stringLength)

Update for Swift 3: enumerate() has been renamed to enumerated():

let mySwiftStringArray = [ "foo", "bar" ]
for (index, string) in mySwiftStringArray.enumerated() {
    print(string)
}
like image 75
Martin R Avatar answered Oct 22 '22 16:10

Martin R


There was an update for Swift 2 on using enumerate().

Instead of enumerate(...), people should use

... .enumerate()

The reason is that many global functions have been replaced by protocol extension methods and they will get an enumerate error.

Hope this helps. All the best. n

like image 5
nigel Avatar answered Oct 22 '22 17:10

nigel