Skip to content

Instantly share code, notes, and snippets.

@yesleon
Last active December 28, 2019 08:45
Show Gist options
  • Save yesleon/cdb114117a8d530ed0500e663ab16630 to your computer and use it in GitHub Desktop.
Save yesleon/cdb114117a8d530ed0500e663ab16630 to your computer and use it in GitHub Desktop.
@dynamicMemberLookup
protocol JSONType {
subscript(dynamicMember member: String) -> JSONType? { get set }
}
extension JSONType {
subscript(dynamicMember member: String) -> JSONType? {
get { nil }
set { }
}
subscript<T>(type: T.Type) -> T? {
get { self as? T }
set {
if self is T, let newValue = newValue as? Self {
self = newValue
}
}
}
}
extension Dictionary: JSONType where Key == String {
subscript(dynamicMember member: String) -> JSONType? {
get { self[member] as? JSONType }
set {
if let newValue = newValue as? Value {
self[member] = newValue
}
}
}
}
extension Optional: JSONType where Wrapped == JSONType {
subscript(dynamicMember member: String) -> JSONType? {
get {
self?[dynamicMember: member]
}
set {
self?[dynamicMember: member] = newValue
}
}
}
extension String: JSONType { }
extension Int: JSONType { }
extension Double: JSONType { }
extension Bool: JSONType { }
extension Array: JSONType { }
var dict: [String: Any] = [
"random": [
"id": 34538560,
"ns": 3,
"title": "User talk:59.188.42.121"
]
]
dict.random.title
dict.random.title[String.self]?.append("sssss")
dict.random.title
dict.random.title[Int.self] = 45
dict.random.title
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment