Skip to content

Instantly share code, notes, and snippets.

@tgnivekucn
Created December 28, 2021 06:09
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 tgnivekucn/7085e6009baa3217d636107c5a4b0e97 to your computer and use it in GitHub Desktop.
Save tgnivekucn/7085e6009baa3217d636107c5a4b0e97 to your computer and use it in GitHub Desktop.
Use copy-on-write semantics for large values
final class Ref<T> {
var val: T
init(_ v: T) {val = v}
}
struct Box<T> {
var ref: Ref<T>
init(_ x: T) { ref = Ref(x) }
var value: T {
get { return ref.val }
set {
if !isKnownUniquelyReferenced(&ref) {
ref = Ref(newValue)
return
}
ref.val = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment