Enum के Basics
एक enum किसी चीज़ के हर possible option को list करता है, जैसे हफ्ते के दिन, ताकि आप गलती से कुछ invalid न चुन लें।
In this page:
Syntax
enum EnumName {
case first, second, third
}
let value = EnumName.first
switch value {
case .first: /* code */
case .second: /* code */
case .third: /* code */
}
Defining an Enum
एक enum case के साथ possible values का एक closed set declare करता है, हर option को एक clear, named identity देते हुए।
उदाहरण: Defining an Enum
// Define an enum `Direction` listing its possible cases
enum Direction {
// Enum case(s): `north, south, east, west`
case north, south, east, west
}
// Declare a constant `heading`, set to `Direction.north`
let heading = Direction.north
// Print `heading` to the console
print(heading)
Login to try C/C++/Java/PHP code in the editor
Using switch with an Enum
चूंकि switch exhaustiveness चाहता है, किसी enum के cases match करना एक natural fit है और compiler सुनिश्चित करता है कि हर case handle हो।
उदाहरण: Using switch with an Enum
// Define an enum `Direction` listing its possible cases
enum Direction {
// Enum case(s): `north, south, east, west`
case north, south, east, west
}
// Declare a constant `heading`, set to `Direction.east`
let heading = Direction.east
// Switch on `heading` and branch by case
switch heading {
// Case: `.north`
case .north:
// Print "Heading north" to the console
print("Heading north")
// Case: `.south`
case .south:
// Print "Heading south" to the console
print("Heading south")
// Case: `.east`
case .east:
// Print "Heading east" to the console
print("Heading east")
case .west:
print("Heading west")
}
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. #}
आम गलतियां
- किसी case को उपयोग करते समय इसे dot से prefix करना भूल जाना, जैसे हर बार पूरी तरह
Direction.northलिखना बजाय shorter.northके जहां type पहले से पता है। - Associated या raw values वाले enum cases को गलत तरीके से
==उपयोग करके compare करना बिना enum कोEquatableconform किए जब custom types के लिए ज़रूरी हो। - एक enum case को एक string constant की तरह treat करना; यह genuinely एक distinct type-safe value है, सिर्फ named text नहीं।
चैप्टर सारांश
- एक
enumrelated, named cases का एक fixed group define करता है। - Cases dot syntax से access होते हैं, जैसे
Direction.northया shorthand.north। switchstatements naturally enums के साथ जोड़े जाते हैं क्योंकि Swift exhaustiveness जांच सकता है।- Enums अपनी खुद की strict, type-safe identity वाली असली value types हैं।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: