Skip to content

Instantly share code, notes, and snippets.

@lokshunhung
Created February 15, 2024 15:16
Show Gist options
  • Save lokshunhung/bb807b01c7ff9c26155957be9ca974f7 to your computer and use it in GitHub Desktop.
Save lokshunhung/bb807b01c7ff9c26155957be9ca974f7 to your computer and use it in GitHub Desktop.
Swift DictionaryKeyPath
public struct DictionaryKey {
public typealias Path = WritableKeyPath<Self, Self>
public var keys: [String]
public init(keys: [String] = []) {
self.keys = keys
}
public subscript(key: String) -> Self {
get {
var keys = keys
keys.append(key)
return Self(keys: keys)
}
set {
keys = newValue.keys
}
}
}
var b: DictionaryKey.Path = \.["b"]["c"]
print(b) // \DictionaryKey.<computed 0x0000000103a7d330 (DictionaryKey)>.<computed 0x0000000103a7d330 (DictionaryKey)>
print(DictionaryKey()[keyPath: b].keys) // ["b", "c"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment