Skip to content

Instantly share code, notes, and snippets.

@noahsark769
Created February 4, 2020 23:11
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save noahsark769/e83f0dc30aced4e805df5cacdb086dd5 to your computer and use it in GitHub Desktop.
Save noahsark769/e83f0dc30aced4e805df5cacdb086dd5 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 Book: KeyPathUpdatable {
var title: String
var author: String
var isbn: Int
var publishedYear: Int
}
let book = Book(title: "Something", author: "Noah", isbn: 1, publishedYear: 2020)
let updated = book.updating(\.title, to: "Else")
print(book)
print(updated)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment