Last active
May 8, 2021 16:39
-
-
Save IanKeen/36e2dd918ac56dbfcc1c63bd43686c0b to your computer and use it in GitHub Desktop.
Naive KeyPath code for dictionaries and arrays
This file contains 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 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