Last active
February 18, 2017 16:54
-
-
Save wh1pch81n/f3ed601fe10d3fd936fef4477dd9766d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// An enum of some planets | |
enum Planets: String { | |
case Mercury | |
case Venus | |
case Earth | |
} | |
// This extension will allow us to use string enums without | |
// explicitly calling rawValue to get the string | |
extension Dictionary where Key: ExpressibleByStringLiteral { | |
subscript(key: Planets) -> Value? { | |
get { return self[key.rawValue as! Key] } | |
set { self[key.rawValue as! Key] = newValue } | |
} | |
} | |
// Using an example dictionary | |
var d = [ | |
"Earth" : "jikyu", | |
"Mercury" : "M" | |
] | |
// retrieving values using the string enum | |
d[Planets.Earth] // "jikyu" | |
d[Planets.Mercury] // "M" | |
// retrieving values using rawValue | |
d[Planets.Earth.rawValue] // "jikyu" | |
d[Planets.Mercury.rawValue] // "M" | |
// Setting a value using the enum | |
d[Planets.Venus] = "The goddess of love" | |
d[Planets.Venus] // "The goddess of love" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment