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

前端 未结 3 1877
小鲜肉
小鲜肉 2020-11-30 05:31

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

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

}

相关标签:
3条回答
  • 2020-11-30 06:01

    I know this is a old thread but I've just been messing around with Swift 2.0 and Playgrounds and I came across the same problem I thought I'd share a solution which uses the enumerate() method for a String

    // This line works in Swift 1.2
    // for (idx, character) in enumerate("A random string, it has a comma.")
    
    // Swift 2.x
    let count = inputString.characters
    
    for (idx, character) in count.enumerate() where character == "," {
    
        // Do something with idx
    }
    

    Hope this helps

    Thanks Kai

    0 讨论(0)
  • 2020-11-30 06:18

    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

    0 讨论(0)
  • 2020-11-30 06:25

    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)
    }
    
    0 讨论(0)
提交回复
热议问题