Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//
// ContentView.swift
// CopyOnWrite
//
// Created by Ray Fix on 3/27/21.
//
import SwiftUI
struct CowType {
init() {
self.detail = Detail(values: Array(repeating: 0, count: 1000))
}
private var detail: Detail
var values: [Int] { detail.values }
mutating func append(_ value: Int) {
if !isKnownUniquelyReferenced(&detail) {
print("performing expensive copy")
detail = Detail(values: values)
}
else {
print("no copy")
}
detail.values.append(value)
}
private final class Detail {
init(values: [Int]) {
self.values = values
}
deinit {
print("calling deinit")
}
var values: [Int]
}
}
final class Model: ObservableObject {
private var state = CowType()
var values: [Int] {
state.values
}
func append(_ value: Int) {
objectWillChange.send()
state.append(value)
}
}
struct ContentView: View {
@StateObject var model = Model()
var body: some View {
VStack {
Text("Hello, world! \(model.values.count)")
.padding()
.gesture(DragGesture().onChanged { _ in
model.append(Int.random(in: 1...100))
})
Text("\(model.values.last!)")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment