Skip to content

Instantly share code, notes, and snippets.

@LucianoPAlmeida
Created November 19, 2017 01:18
Show Gist options
  • Save LucianoPAlmeida/e816b444834232506bad0078b4be0ad3 to your computer and use it in GitHub Desktop.
Save LucianoPAlmeida/e816b444834232506bad0078b4be0ad3 to your computer and use it in GitHub Desktop.
Swift example of How to implement COW for custom value types.
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 (!isUniquelyReferencedNonObjC(&ref)) {
ref = Ref(newValue)
return
}
ref.val = newValue
}
}
}
// This code was an example taken from the swift repo doc file OptimizationTips
// Link: https://github.com/apple/swift/blob/master/docs/OptimizationTips.rst#advice-use-copy-on-write-semantics-for-large-values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment