Skip to content

Instantly share code, notes, and snippets.

@wh1pch81n
Last active February 18, 2017 16:54
Show Gist options
  • Save wh1pch81n/f3ed601fe10d3fd936fef4477dd9766d to your computer and use it in GitHub Desktop.
Save wh1pch81n/f3ed601fe10d3fd936fef4477dd9766d to your computer and use it in GitHub Desktop.
// 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