Created
May 30, 2022 20:46
-
-
Save jakebromberg/de4f7458884f1f4e20e0abff68206372 to your computer and use it in GitHub Desktop.
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
@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