Collections पर Iteration
Iterating का मतलब है किसी collection में हर single item को एक-एक करके visit करना, आमतौर पर हर एक के साथ कुछ करने के लिए।
In this page:
Syntax
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()
// 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)")
}
Login to try C/C++/Java/PHP code in the editor
Iterating a Dictionary
for-in से सीधे किसी dictionary को iterate करना आपको हर entry के लिए (key, value) का एक tuple देता है, जिसे loop header में ही destructure किया जा सकता है।
उदाहरण: Iterating a Dictionary
// 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)")
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- यह भूल जाना कि किसी dictionary को iterate करना
(key, value)tuples देता है, सिर्फ values नहीं। - एक index-based loop उपयोग करना जब collection के elements पर एक direct
for-insimpler और safer होता। .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: