[swift-evolution] [Proposal] Enums with stored properties
Mateusz Malczak
mateusz at malczak.info
Wed Oct 12 06:22:23 CDT 2016
I agree, we dont event have to add a new language syntax to get this
feature. Using structs as rawTypes would do the trick but
1. it should be possible to use struct initializer to define enum cases
struct MyStruct {
var width: Int
var height: Int
init(width: Int, height: Int) { ... }
}
enum MyEnum: MyStruct
{
case myStructCase1(width: 30, height: 30)
case myStructCase2(width: 60, height: 60)
...
}
2. calling .rawVaue should not be required in such case to access
stored properties
let e = MyEnum.myStructCase1
let width = e.width // instead of e.rawValue.width
Immutability of all properties in enum struct type is already
implemented in Swift.
At the same time .rawValue stays as it is for primitive types.
--
| Mateusz Malczak
+-------------------------------
2016-10-12 13:02 GMT+02:00 J.E. Schotsman via swift-evolution
<swift-evolution at swift.org>:
>
> On 12 Oct 2016, at 09:41,Mateusz Malczak wrote:
>
>
> That's exactly what this proposal is about. I would like to
> keep all enum properties but add an extra feature, so that enums can
> store some extra data.
>
>
> If technically possible I would prefer to directly use types for enum cases.
> Reducing a type to a tuple loses the computed properties and methods of the
> type.
> The types must be equatable I suppose.
>
> The current enum rawValues are just indexes or keys which the compiler can
> autogenerate (like it does for enums without a raw type).
> Of course the raw values can be used in some smart way, like for sorting or
> grouping cases, but this can all be done with general types - and better at
> that.
>
> So basically you have a struct type and an enum which is just a set of
> static lets of the struct type.
> struct MyStruct {}
> enum MyEnum: MyStruct
> {
> case myStruct1
> case myStruct2
> ...
> }
>
> MyStruct need not be created specifically for the enum; it might be useful
> on its own.
> MyEnum can have additional computed properties and methods which are needed
> for the enumerated values only.
>
> The cases can be accessed like MyStruct instances. No need for .rawValue
> except in the case of primitive types. Even there there is room for sugar
> (if a variable is already known to be of type Int we can assign an enum:Int
> case to it with implied .rawValue).
>
> Jan E.
>
>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
More information about the swift-evolution
mailing list