Skip to content

Instantly share code, notes, and snippets.

@noahsark769
Created February 5, 2020 01:05
Show Gist options
  • Save noahsark769/e20619a652dc0fb3086ba0843426f56d to your computer and use it in GitHub Desktop.
Save noahsark769/e20619a652dc0fb3086ba0843426f56d to your computer and use it in GitHub Desktop.
protocol KeyPathUpdatable {}
extension KeyPathUpdatable {
func updating<LeafType>(_ keyPath: WritableKeyPath<Self, LeafType>, to value: LeafType) -> Self {
var copy = self
copy[keyPath: keyPath] = value
return copy
}
}
struct Author {
var name: String
}
struct Book: KeyPathUpdatable {
var title: String
var author: Author
var isbn: Int
var publishedYear: Int
}
let book = Book(title: "Something", author: Author(name: "Noah"), isbn: 1, publishedYear: 2020)
let updated = book.updating(\.author.name, to: "Other")
print(book)
print(updated)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment