Skip to content

Instantly share code, notes, and snippets.

@unnamedd
Forked from noahsark769/KeyPathUpdatable.swift
Created February 13, 2020 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unnamedd/63842053c2a764e03ccde6647e068e68 to your computer and use it in GitHub Desktop.
Save unnamedd/63842053c2a764e03ccde6647e068e68 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