[swift-evolution] [Proposal] Allow enumerating cases in enumerations

Gabriel Lanata gabriellanata at gmail.com
Sun Jul 3 20:36:04 CDT 2016


Hello, this has been proposed multiple times before in different ways.

Link to detailed proposal draft:
https://github.com/gabriellanata/swift-evolution/blob/master/proposals/NNNN-allow-enumerating-cases-in-enumerations.md

It is currently not possible to enumerate through all the possible cases of
an enumeration object without adding a hardcoded value or recurring to
unsafe workarounds. The proposal is to add a method of obtaining an array
or set of all the possible cases natively for enumerations without
associated values.

The proposed solution is to implement a native `.cases` static var for all
enumerations without associated values. This would provide a strict
type-safe way of enumerating though the possible cases without risking
runtime errors. The resulting code is a lot cleaner and less prone to
errors caused by forgetting to update the hardcoded values when modifying
cases.

Resulting code:

   enum PokemonType {
       case Fire, Grass, Water, Wind
   }
   for pokemonType in PokemonType.cases {
       // Do stuff
   }
   PokemonType.cases.count // Returns 4


-------
Gabriel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160704/0defeb81/attachment.html>


More information about the swift-evolution mailing list