Skip to content

Instantly share code, notes, and snippets.

@aainaj
Created June 13, 2020 09:42
Show Gist options
  • Save aainaj/877f81be10c2f68373d0972ba555f79c to your computer and use it in GitHub Desktop.
Save aainaj/877f81be10c2f68373d0972ba555f79c to your computer and use it in GitHub Desktop.
KeyPathEditable Protocol
enum KeyPathError: Error {
case unableToCast(String)
}
protocol KeyPathEditable {
func update<KeyPathType>(path: PartialKeyPath<Self>, to value: KeyPathType) throws -> Self
}
extension KeyPathEditable {
func update<KeyPathType>(path: PartialKeyPath<Self>, to value: KeyPathType) throws -> Self {
guard let writableKeyPath = path as? WritableKeyPath<Self, KeyPathType> else {
throw KeyPathError.unableToCast("because of passed \(value) value data type")
}
var copy = self
copy[keyPath: writableKeyPath] = value
return copy
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment