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

CaseIterable क्या है

CaseIterable एक magic label है जिसे आप एक enum पर डालते हैं ताकि Swift आपको इसके हर single option की एक list वापस दे।
Syntax
swift
enum EnumName: CaseIterable {
    case first, second, third
}

for item in EnumName.allCases { }
EnumName.allCases.count

Adopting CaseIterable

किसी enum में CaseIterable conformance जोड़ना अपने आप एक .allCases static property synthesize करता है जो हर case list करती है।

उदाहरण: Adopting CaseIterable

markup
// Define an enum `Direction` listing its possible cases
enum Direction: CaseIterable {
    // Enum case(s): `north, south, east, west`
    case north, south, east, west
}
// Loop over `Direction.allCases`, binding each item to `direction`
for direction in Direction.allCases {
    // Print `direction` to the console
    print(direction)
}

Counting Cases

.allCases.count manually count किए या एक अलग list maintain किए बिना cases की total संख्या देता है।

उदाहरण: Counting Cases

markup
// Define an enum `Direction` listing its possible cases
enum Direction: CaseIterable {
    // Enum case(s): `north, south, east, west`
    case north, south, east, west
}
// Print "Total directions: \(Direction.allCases.count)" to the console
print("Total directions: \(Direction.allCases.count)")
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. किसी enum पर .allCases उपयोग करने की कोशिश करना जो CaseIterable conform नहीं करता; protocol को explicitly adopted होना चाहिए।
  2. यह मान लेना कि CaseIterable associated values वाले enums के लिए अपने आप काम करता है; यह सिर्फ उन enums के लिए काम करता है जिनमें वे नहीं हैं (या जहां Swift सभी possible associated combinations enumerate नहीं कर सकता)।
  3. यह भूल जाना कि .allCases cases को source code में उन्हें declared order में return करता है।
चैप्टर सारांश
  • किसी enum को CaseIterable conform करना अपने आप एक .allCases collection generate करता है।
  • .allCases हर case को declaration order में list करता है।
  • यह सिर्फ associated values के बिना enums के लिए अपने आप काम करता है।
  • .allCases.count यह जानने का एक सुविधाजनक तरीका है कि किसी enum में कितने cases हैं।
🔒

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.