← Back to Swift Course | Chapter 10: Enums | Lesson 1 of 6

Enum के Basics

एक enum किसी चीज़ के हर possible option को list करता है, जैसे हफ्ते के दिन, ताकि आप गलती से कुछ invalid न चुन लें।
Syntax
swift
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

markup
// 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)

Using switch with an Enum

चूंकि switch exhaustiveness चाहता है, किसी enum के cases match करना एक natural fit है और compiler सुनिश्चित करता है कि हर case handle हो।

उदाहरण: Using switch with an Enum

markup
// 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")
}
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. किसी case को उपयोग करते समय इसे dot से prefix करना भूल जाना, जैसे हर बार पूरी तरह Direction.north लिखना बजाय shorter .north के जहां type पहले से पता है।
  2. Associated या raw values वाले enum cases को गलत तरीके से == उपयोग करके compare करना बिना enum को Equatable conform किए जब custom types के लिए ज़रूरी हो।
  3. एक enum case को एक string constant की तरह treat करना; यह genuinely एक distinct type-safe value है, सिर्फ named text नहीं।
चैप्टर सारांश
  • एक enum related, named cases का एक fixed group define करता है।
  • Cases dot syntax से access होते हैं, जैसे Direction.north या shorthand .north।
  • switch statements 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:

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.