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

Raw Values क्या हैं

एक raw value एक plain backup value है, जैसे एक number या letter, जो किसी enum के हर option से permanently चिपकी है।
Syntax
swift
enum EnumName: Type {
    case first = 1, second, third
}

EnumName.first.rawValue
let found = EnumName(rawValue: 2)   // EnumName? (optional)

Declaring Raw Values

Enum नाम के बाद : Type जोड़ना हर case को उस type की एक underlying raw value देता है, .rawValue के ज़रिए accessible।

Note: चूंकि mercury = 1 explicitly सेट किया गया था, Swift बाकी को auto-increment करता है: venus=2, earth=3, mars=4।

उदाहरण: Declaring Raw Values

markup
// Define an enum `Planet` listing its possible cases
enum Planet: Int {
    // Enum case(s): `mercury = 1, venus, earth, mars`
    case mercury = 1, venus, earth, mars
}
// Print `Planet.earth.rawValue` to the console
print(Planet.earth.rawValue)

Creating an Enum from a Raw Value

Failable initializer init?(rawValue:) एक raw value को वापस एक enum case में convert करता है, कोई case match न होने पर nil return करते हुए।

उदाहरण: Creating an Enum from a Raw Value

markup
// Define an enum `Planet` listing its possible cases
enum Planet: Int {
    // Enum case(s): `mercury = 1, venus, earth, mars`
    case mercury = 1, venus, earth, mars
}
// Declare a constant `found`, set to `Planet(rawValue: 3)`
let found = Planet(rawValue: 3)
// Print `found as Any` to the console
print(found as Any)
// Declare a constant `notFound`, set to `Planet(rawValue: 99)`
let notFound = Planet(rawValue: 99)
// Print `notFound as Any` to the console
print(notFound as Any)
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. यह भूल जाना कि raw values सभी एक जैसे type के होने चाहिए और, auto-incrementing Int raw values के लिए, enum के अंदर unique।
  2. किसी enum case की raw value को एक associated value के साथ confuse करना; एक raw value per case definition fixed और shared है, per instance supplied नहीं।
  3. EnumName(rawValue:) से initialize करने की कोशिश करना और यह भूल जाना कि यह एक optional return करता है, क्योंकि हर raw value किसी case से map नहीं होता।
चैप्टर सारांश
  • एक enum एक colon के बाद एक raw value type specify कर सकता है, जैसे String या Int।
  • हर case को एक explicit raw value दी जा सकती है, या Int cases 0 से auto-increment हो सकते हैं।
  • EnumName(rawValue:) एक raw value से एक enum instance बनाता है, एक optional return करते हुए।
  • .rawValue किसी दिए case की underlying raw value retrieve करता है।
🔒

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.