Skip to content

Instantly share code, notes, and snippets.

@kostiakoval
Created July 17, 2015 13:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kostiakoval/17a0da68f3661b3f8d25 to your computer and use it in GitHub Desktop.
Save kostiakoval/17a0da68f3661b3f8d25 to your computer and use it in GitHub Desktop.
Static Safe keys mapping
//: Playground - noun: a place where people can play
import UIKit
var remoteKeys = ["Play", "Stop"]
var LocalKyes = ["1", "2"]
/// Code 1
var keys = [
"Play" : "1",
"Stop" : "2",
"Puppies" : "Puppies_HACK_THE_APP" // Compiler error! No Puppies here
]
keys["Puppies"]
enum Actions : String {
case Play = "Play"
case Stop = "Stop"
}
let items: [Actions: String] = [
.Play : "1",
.Stop : "2",
// .Puppies : "Puppies_HACK_THE_APP" // - Error, yes :)
]
////:1. Extend dictionary
extension Dictionary {
init(_ elements: [Element]){
self.init()
for (k, v) in elements {
self[k] = v
}
}
func map<U>(transform: Key -> U) -> [U : Value] {
return Dictionary<U, Value>(Swift.map(self, { (key, value) in
(transform(key), value) }))
}
}
//:2. Use it and Boom! Happines
let safeKeys = items.map { key in key.rawValue }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment