Created
June 13, 2020 12:43
-
-
Save aainaj/8538fd9a91d84db7174d5d72af21b9c5 to your computer and use it in GitHub Desktop.
ReferenceKeyPathEditable Complete Source code including consumption
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
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