Switch Statement के Basics
switch value {
case pattern1:
// code
case pattern2, pattern3:
// code
default:
// code
}
Basic Switch Syntax
एक switch statement एक value को एक बार evaluate करता है और इसे case patterns की एक series से match करता है, सिर्फ matching block चलाते हुए।
उदाहरण: Basic Switch Syntax
// Declare a constant `day`, set to `3`
let day = 3
// Switch on `day` and branch by case
switch day {
// Case: `1`
case 1:
// Print "Monday" to the console
print("Monday")
// Case: `2`
case 2:
// Print "Tuesday" to the console
print("Tuesday")
// Case: `3`
case 3:
// Print "Wednesday" to the console
print("Wednesday")
default:
// Print "Some other day" to the console
print("Some other day")
}
Login to try C/C++/Java/PHP code in the editor
Matching Multiple Values in One Case
एक single case commas से अलग करके एक साथ कई values match कर सकता है।
उदाहरण: Matching Multiple Values in One Case
// Declare a constant `letter` (a Character), set to `"a"`
let letter: Character = "a"
// Switch on `letter` and branch by case
switch letter {
// Case: `"a", "e", "i", "o", "u"`
case "a", "e", "i", "o", "u":
// Print "\(letter) is a vowel" to the console
print("\(letter) is a vowel")
default:
// Print "\(letter) is a consonant" to the console
print("\(letter) is a consonant")
}
Login to try C/C++/Java/PHP code in the editor
No Implicit Fallthrough
C या Java के विपरीत, Swift के switch cases default रूप से अगले case में fall through नहीं होते -- सिर्फ matching case का code चलता है।
fallthrough keyword जोड़ें।उदाहरण: No Implicit Fallthrough
// Declare a constant `number`, set to `2`
let number = 2
// Switch on `number` and branch by case
switch number {
// Case: `1`
case 1:
// Print "one" to the console
print("one")
// Case: `2`
case 2:
// Print "two" to the console
print("two")
// Case: `3`
case 3:
// Print "three" to the console
print("three")
default:
// Print "other" to the console
print("other")
}
Login to try C/C++/Java/PHP code in the editor
- यह भूल जाना कि Swift के
switchको exhaustive होना चाहिए -- हर possible value handle होनी चाहिए, अक्सर एकdefaultcase की ज़रूरत पड़ती है। - C की तरह cases के बीच implicit fallthrough की उम्मीद करना; Swift cases अपने आप fall through नहीं होते जब तक आप explicitly
fallthroughन लिखें। - एक साधारण two-way boolean check के लिए
switchउपयोग करना जहां एकif-elsesimpler और clearer होता।
switchएक value की तुलना कईcasepatterns से करता है और matching वाला चलाता है।- Swift switches को exhaustive होना चाहिए; एक
defaultcase बाकी बची किसी भी values को cover करता है। - C के विपरीत, cases अपने आप अगले case में fall through नहीं होते।
- एक comma-separated list उपयोग करके एक case में कई values match की जा सकती हैं।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: