Created
March 2, 2020 13:28
-
-
Save lajosdeme/e748a6f225acc13335ab08b3b870ee15 to your computer and use it in GitHub Desktop.
Example of copy-on-write behavior in Swift
This file contains hidden or 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 Person { | |
var name: String | |
init(name: String) { | |
self.name = name | |
} | |
} | |
struct PersonCOW { | |
private var person: Person | |
init(name: String) { | |
person = Person(name: name) | |
} | |
var name: String { | |
get {return person.name} | |
set { | |
if !isKnownUniquelyReferenced(&person) { | |
person = Person(name: newValue) | |
print("Making a copy") | |
} | |
person.name = newValue | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment