Created
November 19, 2017 01:18
-
-
Save LucianoPAlmeida/e816b444834232506bad0078b4be0ad3 to your computer and use it in GitHub Desktop.
Swift example of How to implement COW for custom value types.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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