CaseIterable क्या है
CaseIterable एक magic label है जिसे आप एक enum पर डालते हैं ताकि Swift आपको इसके हर single option की एक list वापस दे।
In this page:
Syntax
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
// 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)
}
Login to try C/C++/Java/PHP code in the editor
Counting Cases
.allCases.count manually count किए या एक अलग list maintain किए बिना cases की total संख्या देता है।
उदाहरण: Counting Cases
// 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)")
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. #}
आम गलतियां
- किसी enum पर
.allCasesउपयोग करने की कोशिश करना जोCaseIterableconform नहीं करता; protocol को explicitly adopted होना चाहिए। - यह मान लेना कि
CaseIterableassociated values वाले enums के लिए अपने आप काम करता है; यह सिर्फ उन enums के लिए काम करता है जिनमें वे नहीं हैं (या जहां Swift सभी possible associated combinations enumerate नहीं कर सकता)। - यह भूल जाना कि
.allCasescases को source code में उन्हें declared order में return करता है।
चैप्टर सारांश
- किसी enum को
CaseIterableconform करना अपने आप एक.allCasescollection 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: