Swift: Extend "enum" enum capabilities to enhance usefulness
| Originator: | christoffer | ||
| Number: | rdar://17259141 | Date Originated: | 11-Jun-2014 00:30 AM |
| Status: | Open | Resolved: | |
| Product: | Developer Tools | Product Version: | Version 6.0 (6A215l) |
| Classification: | Reproducible: | Always |
With java enums, it's possible to store a lot of associated data with each enum value.
With Swift, we're stuck with to/fromRaw and switch/case.
For enum style enums, the following properties are interesting:
So for "enum" enums, there are actually 4 interesting properties:
1. The ordinal used to concisely store the enum.
2. The current "raw type" as the primary way to retrieve the enum that isn't position dependent (the ordinal may change depending on ordering)
3. One or more associated values for each enum case
4. A default string representation for each enum entry that reflects its name in the source code. So enum "FooBar" should have a string representation of "FooBar".
5. Access to an array of all enum values (ordinal ordering)
6. Access to a dictionary of raw value => enum value mapping (or alternatively an array of all raw values)
An example - defining all protocol values:
Swift's current enum
enum Protocol : Int
{
case Login = 1, Welcome = 2 ...
func parameters() -> String[] {
switch (self) {
case Login:
return ["username", "password"]
case Welcome:
return ["image"]
...
}
}
}
What I want:
enum Protocol
{
...
case Login(["username", "password"]) = 1
case Welcome(["image"]) = 2
...
}
Another example:
Swift today:
enum PriceFunction : Int
{
case ExpensivePrice, AffordablePrice, CheapPrice, VeryCheapPrice
func meanValue() {
switch (self) {
case ExpensivePrice:
return 1137.0
case AffordablePrice:
return 401.0
...
func amplitude() {
....
}
What I'd like to see:
enum PriceFunction : Int
{
let meanValue : Double
let amplitude : Double
let periodLength : Double
let ripple : Int
case ExpensivePrice(meanValue: 1137.0, amplitude: 455.0, periodLength: 5.0, ripple: 30) = 0
...
}
Furthermore, one should be able to do something like
Protocol.fromRaw(1) and get Protocol.Login
Protocol.byOrdinal(1) and get Protocol.Welcome
Protocol.all() and get [Procol.Login, Protocol.Welcome]
Protocol.dict() and get [1:Protocol.Login, 2:Protocol.Welcome]
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!