Created
February 15, 2024 15:16
-
-
Save lokshunhung/bb807b01c7ff9c26155957be9ca974f7 to your computer and use it in GitHub Desktop.
Swift DictionaryKeyPath
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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