where Clause की जानकारी
एक where clause किसी चीज़ में एक extra condition जोड़ता है, जैसे कहना "इनमें loop करो, लेकिन सिर्फ वही जो इस test को भी pass करें।"
In this page:
Syntax
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
// 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)")
}
Login to try C/C++/Java/PHP code in the editor
where in a switch Case
एक switch में एक case बस value की shape match करने से आगे एक additional condition मांगने के लिए एक where clause जोड़ सकता है।
उदाहरण: where in a switch Case
// 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))")
}
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. #}
आम गलतियां
- Loop-level
whereclause (जो iterations filter करता है) कोswitchcasewhere(जो एक match condition जोड़ता है) के साथ confuse करना -- ये similar दिखते हैं लेकिन अलग तरीके से apply होते हैं। - Loop body के अंदर एक अलग
ifलिखना जब loop पर खुद एकwhereclause ज़्यादा clean होता और non-matching elements को पूरी तरह skip कर देता। - यह भूल जाना कि for-loop में
whereअब भी हर element पर iterate करता है -- यह सिर्फ non-matching वालों के लिए body skip करता है, यह underlying collection filter नहीं करता।
चैप्टर सारांश
- एक
for-inloop पर एकwhereclause filter करता है कि कौन सी iterations अपना body चलाएं। - एक
switchcase पर एकwhereclause सिर्फ pattern matching से आगे एक extra condition जोड़ता है। wherefiltering 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: