[swift-evolution] [Idea] Find alternatives to `switch self`
Erica Sadun
erica at ericasadun.com
Wed Mar 23 23:36:42 CDT 2016
> On Mar 23, 2016, at 9:23 PM, Kevin Lundberg via swift-evolution <swift-evolution at swift.org> wrote:
>
> This can be done today with no syntax changes (you'd have to return optional or handle the nil case though):
>
> var description: String? {
> return [
> .Hearts: "♥️",
> .Spades: "♠️",
> .Diamonds: "♦️",
> .Clubs: "♣️"
> ][self]
> }
You could always use nil-coalescing
return [
.Hearts: "♥️",
.Spades: "♠️",
.Diamonds: "♦️",
.Clubs: "♣️"
][self ] ?? "won't happen"
Or do something silly like this:
public extension Dictionary {
public subscript(key: Key, fallback: Value) -> Value {
return self[key] ?? fallback
}
}
enum Suits {
case Hearts, Spades, Diamonds, Clubs
var description: String {
let values: [Suits: String] = [
.Hearts: "♥️",
.Spades: "♠️",
.Diamonds: "♦️",
.Clubs: "♣️"
]
return values[self, "?"]
}
}
Even thought they kind of sort of work, I don't like either one.
-- E
More information about the swift-evolution
mailing list