Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Last active May 8, 2021 16:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanKeen/36e2dd918ac56dbfcc1c63bd43686c0b to your computer and use it in GitHub Desktop.
Save IanKeen/36e2dd918ac56dbfcc1c63bd43686c0b to your computer and use it in GitHub Desktop.
Naive KeyPath code for dictionaries and arrays
public protocol KeyPathComponent { }
extension String: KeyPathComponent { }
extension Int: KeyPathComponent { }
public protocol KeyPathAccessible {
func value<T>(at component: KeyPathComponent) -> T?
}
extension KeyPathAccessible {
private func component(at component: KeyPathComponent) -> KeyPathAccessible? {
return value(at: component)
}
public func value<T>(at start: KeyPathComponent, _ rest: KeyPathComponent...) -> T? {
guard !rest.isEmpty else { return self.value(at: start) }
return rest
.dropLast()
.reduce(component(at: start)) { acc, next in acc.flatMap { $0.component(at: next) } }?
.value(at: rest.last!)
}
}
extension Dictionary: KeyPathAccessible {
public func value<T>(at component: KeyPathComponent) -> T? {
return (component as? Key).flatMap { self[$0] as? T }
}
}
extension Array: KeyPathAccessible {
public func value<T>(at component: KeyPathComponent) -> T? {
return (component as? Int).flatMap { self[$0] as? T }
}
}
import Foundation
extension NSArray: KeyPathAccessible {
public func value<T>(at component: KeyPathComponent) -> T? { return (self as Array).value(at: component) }
}
extension NSDictionary: KeyPathAccessible {
public func value<T>(at component: KeyPathComponent) -> T? { return (self as Dictionary).value(at: component) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment