[swift-evolution] [Idea] Find alternatives to `switch self`

Sean Heber sean at fifthace.com
Thu Mar 31 10:36:59 CDT 2016


I like this. I might be inclined to do something a bit more like this, though, syntax-wise:

enum Suit {
  let description: String
  var isRed = false

  case hearts {
    description = "♥️"
    isRed = true
  }
  case spades {
    description = "♠️"
  }
  case diamonds {
    description = “♦️"
    isRed = true
  }
  case clubs {
    description = “♣️"
  }
}

By the end of the enum {} you must provide a value for every property declared in the enum or else it’d be a compile error. If you declare one as “var”, then you can specify a default value that can be overridden by just a few cases such as the “isRed” example. Declaring a property as “let” means every case must supply their own value for it. (If something is declared as var but each case supplies a value, there’d be a warning to turn the “var” into a “let”.)

However just because the property is declared as var doesn’t mean you can actually arbitrarily change it externally:

var foo = Suit.hearts
foo.isRed = false  // error - enum values are immutable

l8r
Sean



> On Mar 31, 2016, at 7:15 AM, Radosław Pietruszewski via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> On 23 Mar 2016, at 11:13, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> 
>> * Allow you to attach member definitions to particular cases. It would be an error if they didn't all define the same members, unless there was a top-level catchall.
>> 
>>    enum Suit: Int {
>>        var isRed: Bool { return false }
>> 
>>        case Hearts {
>>            let description: String { return "♥️" }
>>            let isRed: Bool { return true }
>>        }
>>        case Spades {
>>            let description: String { return  "♠️" }
>>        }
>>        case Diamonds {
>>            let description: String { return  "♦️" }
>>            let isRed: Bool { return true }
>>        }
>>        case Clubs {
>>            let description: String { return  "♣️" }
>>        }
>> 
>>        static var all = [ Hearts, Spades, Diamonds, Clubs ]
>>    }
> 
> Ah, that’s interesting! This would make enum cases less like values, and more like their own types.
> 
> (Or maybe not — it’s still a property of the enum itself, and the definitions must cover all cases. But it does suggest a different way of thinking about what enum cases are. Maybe it would be a good thing to have enum cases be more like types, and have their own properties and stuff? I don’t know…)
> 
> — Radek
> 
> _______________________________________________
> 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