for-in Loop की जानकारी
for item in collection {
// use item
}
for i in 1...5 { } // closed range
for i in 0..<count { } // half-open range
Iterating Over a Range
एक for-in loop एक numeric range पर iterate कर सकता है, उस range में हर value के लिए body एक बार चलाते हुए।
उदाहरण: Iterating Over a Range
// Loop over `1...5`, binding each item to `i`
for i in 1...5 {
// Print "Count: \(i)" to the console
print("Count: \(i)")
}
Login to try C/C++/Java/PHP code in the editor
Iterating Over an Array
वही for-in syntax सीधे एक array पर काम करता है, आपको order में हर element देते हुए।
उदाहरण: Iterating Over an Array
// Declare a constant `fruits`, set to `["apple", "banana", "cherry"]`
let fruits = ["apple", "banana", "cherry"]
// Loop over `fruits`, binding each item to `fruit`
for fruit in fruits {
// Print "Fruit: \(fruit)" to the console
print("Fruit: \(fruit)")
}
Login to try C/C++/Java/PHP code in the editor
Half-Open vs Closed Ranges
..< एक half-open range बनाता है जो इसकी upper bound को exclude करता है, जबकि ... एक closed range बनाता है जो इसे include करता है -- array indices पर loop करते समय एक महत्वपूर्ण distinction।
0..<numbers.count bounds से बाहर गए बिना valid indices पर loop करने का idiomatic तरीका है।उदाहरण: Half-Open vs Closed Ranges
// Declare a constant `numbers`, set to `[10, 20, 30]`
let numbers = [10, 20, 30]
// Loop over `0..<numbers.count`, binding each item to `index`
for index in 0..<numbers.count {
// Print "Index \(index): \(numbers[index])" to the console
print("Index \(index): \(numbers[index])")
}
Login to try C/C++/Java/PHP code in the editor
- एक C-style
for i = 0; i < n; i++loop उपयोग करना; वह syntax Swift से पूरी तरह हटाया गया -- इसके बजायfor i in 0..<nउपयोग करें। - Closed range
...(दोनों ends include करता है) को half-open range..<(upper end exclude करता है) के साथ confuse करना। - Loop body के अंदर loop variable modify करने की कोशिश करना इस उम्मीद से कि यह iteration को प्रभावित करे; loop variable हर iteration में एक fresh constant है।
for item in collectionकिसी array, range, dictionary, या अन्य sequence के हर element पर iterate करता है।0..<5एक half-open range है 5 को exclude करते हुए;0...5closed है और 5 include करता है।- Loop variable default रूप से एक constant है, हर iteration में फिर से bound।
- for-in arrays, ranges, strings, dictionaries, और
Sequenceconform करने वाली किसी भी type पर काम करता है।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: