Pattern Matching क्या है
In this page:
switch (a, b) {
case (0, let y): // tuple pattern
// code
case 1...10: // range pattern
// code
default: break
}
if case pattern = value { }
Matching Tuples
एक switch किसी tuple की shape के खिलाफ match कर सकता है, और case let bindings आपको इसके individual components निकालने देते हैं।
उदाहरण: Matching Tuples
// Declare a constant `coordinate`, set to `(0, 5)`
let coordinate = (0, 5)
// Switch on `coordinate` and branch by case
switch coordinate {
// Case: `(0, 0)`
case (0, 0):
// Print "Origin" to the console
print("Origin")
// Case: `(0, let y)`
case (0, let y):
// Print "On the y-axis at \(y)" to the console
print("On the y-axis at \(y)")
// Case: `(let x, 0)`
case (let x, 0):
// Print "On the x-axis at \(x)" to the console
print("On the x-axis at \(x)")
// Case: `let (x, y)`
case let (x, y):
// Print "At (\(x), \(y))" to the console
print("At (\(x), \(y))")
}
Login to try C/C++/Java/PHP code in the editor
Matching Ranges
एक case किसी value को एक numeric range के खिलाफ match कर सकता है, जो values को categories में group करने के लिए उपयोगी है।
उदाहरण: Matching Ranges
// Declare a constant `score`, set to `85`
let score = 85
// Switch on `score` and branch by case
switch score {
// Case: `90...100`
case 90...100:
// Print "Grade: A" to the console
print("Grade: A")
// Case: `80..<90`
case 80..<90:
// Print "Grade: B" to the console
print("Grade: B")
default:
// Print "Grade: C or below" to the console
print("Grade: C or below")
}
Login to try C/C++/Java/PHP code in the editor
if case for Single-Value Matching
जब आपको सिर्फ एक पूरे switch के बिना एक pattern test करना हो, if case एक lightweight alternative प्रदान करता है।
उदाहरण: if case for Single-Value Matching
// Declare a constant `value` (a `Int?`), set to `7`
let value: Int? = 7
// Check whether `case .some(let number) = value`
if case .some(let number) = value {
// Print "Got a number: \(number)" to the console
print("Got a number: \(number)")
}
Login to try C/C++/Java/PHP code in the editor
- यह सोचना कि pattern matching सिर्फ enums पर
switchके लिए है; यह tuples, ranges, और optional binding के साथ भी काम करता है। - यह भूल जाना कि एक
case letpattern नए local constants bind करता है जो सिर्फ उस case की body के अंदर मौजूद हैं। - यह नज़रअंदाज़ करना कि case order मायने रखता है -- एक
switchमें पहले एक broader pattern बाद में लिखे गए एक ज़्यादा specific को shadow कर देगा।
- Swift में Pattern matching
switch,if case, औरfor caseconstructs में दिखता है। - Tuple patterns कई values match कर सकते हैं और एक साथ इन्हें destructure कर सकते हैं।
- Range patterns (
case 1...5) एक value को match करते हैं जो उस range के अंदर आता है। if caseआपको एक पूरे switch statement के बिना एक single value pattern-match करने देता है।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: