← Back to Swift Course | Chapter 6: Collections | Lesson 5 of 7

Collections पर Iteration

Iterating का मतलब है किसी collection में हर single item को एक-एक करके visit करना, आमतौर पर हर एक के साथ कुछ करने के लिए।
Syntax
swift
for (index, element) in array.enumerated() {
    // index and element
}

for (key, value) in dictionary {
    // each pair
}

Iterating an Array with enumerated()

.enumerated() हर element को उसके index के साथ जोड़ता है, आपको एक for-in loop के अंदर दोनों को एक साथ access करने देते हुए।

उदाहरण: Iterating an Array with enumerated()

markup
// Declare a constant `colors`, set to `["red", "green", "blue"]`
let colors = ["red", "green", "blue"]
for (index, color) in colors.enumerated() {
    // Print "\(index): \(color)" to the console
    print("\(index): \(color)")
}

Iterating a Dictionary

for-in से सीधे किसी dictionary को iterate करना आपको हर entry के लिए (key, value) का एक tuple देता है, जिसे loop header में ही destructure किया जा सकता है।

उदाहरण: Iterating a Dictionary

markup
// Declare a constant `ages`, set to `["Alice": 30, "Bob": 25]`
let ages = ["Alice": 30, "Bob": 25]
for (name, age) in ages {
    // Print "\(name) is \(age)" to the console
    print("\(name) is \(age)")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि किसी dictionary को iterate करना (key, value) tuples देता है, सिर्फ values नहीं।
  2. एक index-based loop उपयोग करना जब collection के elements पर एक direct for-in simpler और safer होता।
  3. .enumerated() के मौजूद होने के बारे में न जानना, और इसके बजाय manually एक index counter variable track करना।
चैप्टर सारांश
  • for-in सीधे किसी array के elements, किसी set के members, या किसी dictionary के key-value pairs पर iterate करता है।
  • .enumerated() किसी array iterate करते समय index और element दोनों एक साथ प्रदान करता है।
  • किसी dictionary को iterate करना tuples yield करता है जिन्हें अलग key और value constants में destructure किया जा सकता है।
  • Sets arrays के विपरीत एक unspecified order में iterate होते हैं, जो insertion order संरक्षित रखते हैं।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.