Skip to content

Instantly share code, notes, and snippets.

@ionel71089
Created August 26, 2016 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ionel71089/ea196d90bcd2c6b2e25c6e837626dbc8 to your computer and use it in GitHub Desktop.
Save ionel71089/ea196d90bcd2c6b2e25c6e837626dbc8 to your computer and use it in GitHub Desktop.
get/set values from dictionary with a path
//: Playground - noun: a place where people can play
import UIKit
extension Array {
private var x:Element? { return self.first }
private var xs: [Element] { return [Element](self.dropFirst()) }
var parts: (Element?, [Element]) {
return (self.x, self.xs)
}
}
extension Dictionary {
subscript(path: [Key]) -> Any? {
get {
let (x, xs) = path.parts
switch (x, xs) {
case (let .Some(key), _) where xs.count == 0:
return self[key]
case (let .Some(key), _) where xs.count > 0:
if let sub = self[key] as? Dictionary<Key, AnyObject> {
return sub[xs]
}
default:
break
}
return nil
}
set {
let (x, xs) = path.parts
switch (x, xs) {
case (let .Some(key), _) where xs.count == 0:
self[key] = newValue as? Value
case (let .Some(key), _) where xs.count > 0:
var sub = self[key] as? Dictionary<Key, AnyObject>
if sub == nil {
sub = Dictionary<Key,AnyObject>()
}
sub![xs] = newValue
self[key] = sub as? Value
default:
break
}
}
}
}
var dictionary: [String: AnyObject] = [
"a":
[
"b":
[
"c": "result"
]
]
]
let path = "a/b/c".componentsSeparatedByString("/")
print("\ndictionary: \(dictionary) \npath: \(path) \nvalue: \(dictionary[path])")
dictionary[path] = "another result"
print()
print("\ndictionary: \(dictionary) \npath: \(path) \nvalue: \(dictionary[path])")
print()
print(dictionary[[]])
dictionary[[]] = "q"
print(dictionary[[]])
let path2 = "z/y/x".componentsSeparatedByString("/")
print("\ndictionary: \(dictionary) \npath: \(path2) \nvalue: \(dictionary[path2])")
dictionary[path2] = "another result"
print()
print("\ndictionary: \(dictionary) \npath: \(path2) \nvalue: \(dictionary[path2])")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment