← Back to Swift Course | Chapter 3: Control Flow | Lesson 7 of 8

where Clause की जानकारी

एक where clause किसी चीज़ में एक extra condition जोड़ता है, जैसे कहना "इनमें loop करो, लेकिन सिर्फ वही जो इस test को भी pass करें।"
Syntax
swift
for item in collection where condition {
    // only items matching the condition
}

switch value {
case let x where condition:
    // code
default: break
}

where in a for-in Loop

Loop variable के बाद where जोड़ना filter करता है कि कौन से elements असल में loop body execute करते हैं, उन्हें skip करते हुए जो condition satisfy नहीं करते।

उदाहरण: where in a for-in Loop

markup
// Loop over `1...10 where number % 3 == 0`, binding each item to `number`
for number in 1...10 where number % 3 == 0 {
    // Print "Multiple of 3: \(number)" to the console
    print("Multiple of 3: \(number)")
}

where in a switch Case

एक switch में एक case बस value की shape match करने से आगे एक additional condition मांगने के लिए एक where clause जोड़ सकता है।

उदाहरण: where in a switch Case

markup
// Declare a constant `point`, set to `(2, 2)`
let point = (2, 2)
// Switch on `point` and branch by case
switch point {
// Case: `let (x, y) where x == y`
case let (x, y) where x == y:
    // Print "Point is on the diagonal" to the console
    print("Point is on the diagonal")
// Case: `let (x, y)`
case let (x, y):
    // Print "Point at (\(x), \(y))" to the console
    print("Point at (\(x), \(y))")
}
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. Loop-level where clause (जो iterations filter करता है) को switch case where (जो एक match condition जोड़ता है) के साथ confuse करना -- ये similar दिखते हैं लेकिन अलग तरीके से apply होते हैं।
  2. Loop body के अंदर एक अलग if लिखना जब loop पर खुद एक where clause ज़्यादा clean होता और non-matching elements को पूरी तरह skip कर देता।
  3. यह भूल जाना कि for-loop में where अब भी हर element पर iterate करता है -- यह सिर्फ non-matching वालों के लिए body skip करता है, यह underlying collection filter नहीं करता।
चैप्टर सारांश
  • एक for-in loop पर एक where clause filter करता है कि कौन सी iterations अपना body चलाएं।
  • एक switch case पर एक where clause सिर्फ pattern matching से आगे एक extra condition जोड़ता है।
  • where filtering conditions को loop या case header के हिस्से के रूप में naturally पढ़ाता है।
  • यह pattern matching, generics, और protocol constraints के साथ विशेष रूप से उपयोगी है (बाद के chapters में ज़्यादा देखा जाएगा)।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 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.