Created
June 28, 2018 22:05
-
-
Save airspeed/097baa6e9ecf69fb9c0eb8872d15ae4f to your computer and use it in GitHub Desktop.
copy-on-write
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 Content { | |
var value: Int | |
init(value: Int) { self.value = value } | |
var debug: String { return String(describing: value) } | |
} | |
struct Wrapper { | |
private var _content: Content | |
var content: Content { | |
mutating get { | |
if !isKnownUniquelyReferenced(&_content) { | |
print("copy") | |
_content = Content(value: _content.value) | |
} | |
return _content | |
} | |
} | |
init(content: Content) { | |
self._content = content | |
} | |
var debug: String { return String(describing: _content.value) } | |
} | |
extension Wrapper: CustomStringConvertible { | |
public var description: String { | |
return self.debug | |
} | |
} | |
extension Content: CustomStringConvertible { | |
public var description: String { | |
return self.debug | |
} | |
} | |
var m = Wrapper(content: Content(value: 9)) | |
var n = m | |
n.content.value = 11 | |
n | |
m | |
// safe copy-on-write semantics implemented | |
// sources: http://chris.eidhof.nl/post/struct-semantics-in-swift/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment