[swift-evolution] [Proposal] Enums with static stored properties for each case

Vladimir.S svabox at gmail.com
Fri May 27 06:05:20 CDT 2016

Correct me if I'm wrong, but this idea with accessors is not the same as 
static properties for each case. The one of ideas of initial proposal - 
static(!) values would be created only once and it is important in case it 
is expensive to create such value(or if should be created only once per case)

The suggested solution based on 'accessor' - will create assotiated 
properties each time the enum instace created, for each instance of enum type.

We can have something like the example with accessors now :

enum MyError: ErrorProtocol {
     struct MyErrorInfo {
         let localizedFailureReason: String
         let url: String

     case fileNotFound(url: String)
     case fileIsCorrupt(url: String)

     var info : MyErrorInfo {
         switch self {
             case fileNotFound(let url) : return 
MyErrorInfo(localizedFailureReason: "File \"\(url.lowercased())\" not 
found.", url: url)

             case fileIsCorrupt(let url) : return 
MyErrorInfo(localizedFailureReason: "File \"\(url.lowercased())\"  is 
corrupt.", url: url)

var e = MyError.fileNotFound(url: "http://something.some")
var info = e.info
print(info.localizedFailureReason, info.url)

But yes, such MyErrorInfo will be created on each `info.` call. This is 
worse that create MyErrorInfo once per each enum instance initialization, 
but IMO these solutions are close enough.

In any case, I don't see why tuple for enum and enum with `accessor` can 
not co-exists.

On 27.05.2016 2:28, Charles Srstka via swift-evolution wrote:
>> On May 26, 2016, at 4:47 PM, Brent Royal-Gordon via swift-evolution
>> <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> - Abusing rawValue is just that: an abuse.
> In addition, enums with associated types can’t have rawValues.
> Why is this relevant, you may ask? Because error enums are a huge use case
> for something like this. Being able to do the below would be great:
> enum MyError: ErrorProtocol {
>     accessor var localizedFailureReason: String
>     accessor var url: NSURL
>     case FileNotFound(url: NSURL) {
>         self.localizedFailureReason = “File \"\(url.lastPathComponent ??
> “”)\” not found.”
>         self.url = url
>     }
>     case FileIsCorrupt(url: NSURL) {
>         self.localizedFailureReason = “File \"\(url.lastPathComponent ??
> “”)\” is corrupt.”
>         self.url = url
>     }
> }
> This would be much cleaner than the existing method of using a switch to
> create a userInfo dictionary for creating an NSError to send to
> -[NSApplication presentError:] and similar methods.
> Charles
> _______________________________________________
> 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