Skip to content

Instantly share code, notes, and snippets.

@rex-remind101
Last active August 28, 2023 04:40
Show Gist options
  • Save rex-remind101/60ee8059b2a4f952b0c4d56ebb32f1f7 to your computer and use it in GitHub Desktop.
Save rex-remind101/60ee8059b2a4f952b0c4d56ebb32f1f7 to your computer and use it in GitHub Desktop.
Copy-On-Write Swift Property Wrapper
final private class Ref<T> {
var value: T
init(_ v: T) { self.value = v }
}
@propertyWrapper
public struct CopyOnWrite<T> {
private var ref: Ref<T>
public init(_ value: T) {
self.ref = Ref(value)
}
public init(wrappedValue: T) {
self = Self(wrappedValue)
}
public var wrappedValue: T {
@inline(__always)
get { self.ref.value }
@inline(__always)
set {
if isKnownUniquelyReferenced(&self.ref) {
self.ref.value = newValue
} else {
self.ref = Ref(newValue)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment