Maybe the dictionary literal syntax could be used as a shorthand?
enum Suit: Int {
case Hearts, Spades, Diamonds, Clubs
var description: String {
return switch self [
.Hearts: "
",
.Spades: "
",
.Diamonds: "
",
.Clubs: "
"
]
}
var isRed: Bool {
return switch self [
.Hearts: true,
.Diamonds: true,
.Spades: false,
.Clubs: false
]
}
}
Patrick
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]
}
···
On 3/23/2016 8:42 PM, Patrick Smith via swift-evolution wrote:
Maybe the dictionary literal syntax could be used as a shorthand?
enum Suit: Int {
case Hearts, Spades, Diamonds, Clubs
var description: String {
return switch self [
.Hearts: "
",
.Spades: "
",
.Diamonds: "
",
.Clubs: "
"
]
}
var isRed: Bool {
return switch self [
.Hearts: true,
.Diamonds: true,
.Spades: false,
.Clubs: false
]
}
}
Patrick
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution
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
···
On Mar 23, 2016, at 9:23 PM, Kevin Lundberg via swift-evolution <swift-evolution@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]
}
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 have to handle the nil case" is a symptom of the real problem with this approach: you lose exhaustiveness checking.
···
--
Brent Royal-Gordon
Architechies
1 Like