Raw Values क्या हैं
एक raw value एक plain backup value है, जैसे एक number या letter, जो किसी enum के हर option से permanently चिपकी है।
In this page:
Syntax
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
// 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)
Login to try C/C++/Java/PHP code in the editor
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
// 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)
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. #}
आम गलतियां
- यह भूल जाना कि raw values सभी एक जैसे type के होने चाहिए और, auto-incrementing
Intraw values के लिए, enum के अंदर unique। - किसी enum case की raw value को एक associated value के साथ confuse करना; एक raw value per case definition fixed और shared है, per instance supplied नहीं।
EnumName(rawValue:)से initialize करने की कोशिश करना और यह भूल जाना कि यह एक optional return करता है, क्योंकि हर raw value किसी case से map नहीं होता।
चैप्टर सारांश
- एक enum एक colon के बाद एक raw value type specify कर सकता है, जैसे
StringयाInt। - हर case को एक explicit raw value दी जा सकती है, या
Intcases 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: