Above The Gods
Above The Gods

Reputation: 175

How to get index in for case pattern matching loop

I have a for case loop in which I want to sort the created variables using their index from that loop. However, I'm not sure if there's an elegant way of doing so. here is the loop I have so far.

typealias JSONDictionary = [String: AnyObject]

for case let playlistData as JSONDictionary in JSON {
        let playlist = Playlist(context: coreData.viewContext)
        playlist.initialize(dictionary: playlistData, key: youtube.GMSKey)

Here's what I want to avoid:

       typealias JSONDictionary = [String: AnyObject]

       var i = 0
        for case let playlistData as JSONDictionary in JSON {
            let playlist = Playlist(context: coreData.viewContext)
            playlist.initialize(dictionary: playlistData, key: youtube.GMSKey)
            // etc
            i += 1 

Upvotes: 1

Views: 519

Answers (2)

Hamish
Hamish

Reputation: 80901

You can use enumerated() in conjunction with for case let, you just need to move the conditional typecasting pattern into the binding of the second element in the tuple.

// note that variable names should be lowerCamelCase – I renamed 'JSON' to 'json'.
for case let (index, playlistData as JSONDictionary) in json.enumerated() {
    // ...
}

enumerated() returns a sequence of pairs of consecutive Ints starting from 0 (available inside the loop as index) along with the elements of the sequence you call it on.

Upvotes: 4

azizj
azizj

Reputation: 3787

for case (index, element as JSONDictionary) in JSON.enumerated() {
  print("Item \(index): \(element)")
}

or

for (index, element) in JSON.enumerated() {
  if element as JSONDictionary {
   //
  }
}

Upvotes: 2

Related Questions