[swift-evolution] [Proposal] Enums with stored properties

Haravikk swift-evolution at haravikk.me
Mon Oct 10 08:31:17 CDT 2016


> On 10 Oct 2016, at 13:04, Mateusz Malczak via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I think, I have used quite unfortunate naming, which is a root of an
> misunderstanding here. By saying 'enums with stored properties' what I
> was really thinking about, was enumeration type with stored constant,
> immutable properties (constants). I don't want to duplicate 'struct'
> type here, but instead I would like to make it possible to store a
> const values in enumeration cases. So going back to my example once
> again:
> 
> Lest define an enumeration type `Format` with 3 possible cases. Each
> case will be able to carry over some additional information - in this
> case a pair of numbers (but in fact Any? should be possible)
> 
> enum Format {
>    case SMALL(30, 30)
>    case MEDIUM(60, 60)
>    case LARGE(120, 120)
>    var width: Double
>    var height: Double
>    init(width: Double, height: Double) {
>        self.width = width
>        self.height = height
>    }
> }
> 
> I'm not sure about 'var' clause in that example as it causes all the confusion.
> 
> I can access additional info stored in enum case, but it cannot be
> modified. Format.SMALL doesn't change, as well as non of its
> properties.
> 
> // allowed usage
> let format = Format.SMALL
> let width = format.width // this would be equal to 30 (const value
> assigned to 'width' property on enum case .SMALL)
> 
> // not allowed usage
> let format = Format.SMALL
> format.width = 40 // error, stored values are immutable and can not be modified
> 
> We get all advantages of enumeration type, and, assuming all cases are
> describing the same possible state, we can store some extra
> information in each case. This can be called a third enumeration type
> feature, right next to associated values and rawType.
> 
> --
> | Mateusz Malczak

Can't this problem most easily be solved by a raw value? Like so:

enum Format : Int {
    case small = 30
    case medium = 60
    case large = 120

    var width:Int { return self.rawValue }
    var height:Int { return self.rawValue }
}

Granted this becomes more complex if you want to specify widths and heights that do not match, as you can't currently specify a tuple as the raw value, but if you could then that seems like it would be a better solution to this problem surely?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161010/a080f0a0/attachment.html>


More information about the swift-evolution mailing list