Skip to content

Instantly share code, notes, and snippets.

@rayfix
Created April 3, 2021 19:46
Show Gist options
  • Save rayfix/dc079e527be76f9be4a419ca2896d5ba to your computer and use it in GitHub Desktop.
Save rayfix/dc079e527be76f9be4a419ca2896d5ba to your computer and use it in GitHub Desktop.
//
// 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