Post

Replies

Boosts

Views

Activity

Copy-on-write types and SwiftUI
I am trying to use a custom Copy-on-write type with SwiftUI. I have found that it takes the expensive path every time in the below code. Any thoughts about how I can avoid the copy and deinit for every drag event? Thanks for any insights or hints you might have. swift struct CowType {   init() {     self.detail = Detail(values: [])   }   private var detail: Detail   var values: [Int] { detail.values }   mutating func appendValue(_ value: Int) {     if !isKnownUniquelyReferenced(&detail) {       print("performing expensive copy")       detail = Detail(values: values)     }     detail.values.append(value)   }   private final class Detail {     init(values: [Int]) {       self.values = values     }     deinit {        print("calling deinit")     }     var values: [Int]   } } struct ContentView: View {   @State var state = CowType()   var body: some View {     Text("Hello, world! \(state.values.count)")       .padding()       .gesture(DragGesture().onChanged { _ in         state.appendValue(Int.random(in: 1...100))       })   } }
3
0
1.3k
Mar ’21