Skip to content

Instantly share code, notes, and snippets.

@jakebromberg
Created May 30, 2022 20:46
Show Gist options
  • Save jakebromberg/de4f7458884f1f4e20e0abff68206372 to your computer and use it in GitHub Desktop.
Save jakebromberg/de4f7458884f1f4e20e0abff68206372 to your computer and use it in GitHub Desktop.
@propertyWrapper
struct CopyOnWrite<Object> {
var wrappedValue: Object {
get { storage.object }
set {
if !isKnownUniquelyReferenced(&storage) {
storage = storage.copy()
}
storage.object = newValue
}
}
public init(wrappedValue: Object) {
storage = Storage(wrappedValue)
}
private var storage: Storage
private class Storage {
var object: Object
init(_ object: Object) {
self.object = object
}
func copy() -> Storage {
print("Copying")
return Storage(object)
}
}
}
struct HTTPRequest {
@CopyOnWrite var path: String
@CopyOnWrite var headers: [String:String]
}
var reqA = HTTPRequest(path: "/home", headers: [:])
print("Assigning to B")
var reqB = reqA
print("Mutating B")
reqB.headers["X-RequestId"] = "\(5)"
print(reqA.headers, reqB.headers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment