Skip to content

Instantly share code, notes, and snippets.

@aainaj
Created June 13, 2020 12:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aainaj/8538fd9a91d84db7174d5d72af21b9c5 to your computer and use it in GitHub Desktop.
Save aainaj/8538fd9a91d84db7174d5d72af21b9c5 to your computer and use it in GitHub Desktop.
ReferenceKeyPathEditable Complete Source code including consumption
enum KeyPathError: Error {
case unableToCast(String)
}
protocol ReferenceKeyPathEditable {
associatedtype Root
func update<KeyPathType>(type: Root, path: PartialKeyPath<Root>, to value: KeyPathType) throws
}
extension ReferenceKeyPathEditable {
func update<KeyPathType>(type: Root, path: PartialKeyPath<Root>, to value: KeyPathType) throws {
guard let writableKeyPath = path as? ReferenceWritableKeyPath<Root, KeyPathType> else {
throw KeyPathError.unableToCast("because of passed \(value) value data type")
}
type[keyPath: writableKeyPath] = value
}
}
class Merchant: ReferenceKeyPathEditable {
typealias Root = Merchant
private(set) var name: String
private(set) var occupation: String
init(name: String, occupation: String) {
self.name = name
self.occupation = occupation
}
}
let merchant = Merchant(name: "Ryan", occupation: "Grocery Business")
print("** Initial: \(merchant.occupation) **")
try? merchant.update(type: merchant, path: \Merchant.occupation, to: "Furniture Business")
print("** Updated: \(merchant.occupation) **")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment