-3

Swift version 5.3.1
Xcode 12.2

As title.
When I update delta.a.value or delta.b.value that will auto calculate delta.value. Delta.value is related to UI
Is it a good way in Swift?

struct Component {
    var value = 0
}

struct Delta {
    let a: Component
    let b: Component
    var value = 0       //  equation: a.value - b.value
    
    init(a: Component, b: Component) {
        self.a = a
        self.b = b
    }
}

let a = Component()
let b = Component()
let delta = Delta(a: a, b: b)
delta.a.value = 100
delta.b.value = 20
//  result: delta.value = 80

CocoaUser
  • 1,361
  • 1
  • 15
  • 30
  • 2
    How is what you are asking related to KVO? It seems like you just want a _computed property_. – Sweeper Dec 03 '20 at 06:51
  • @Sweeper I want to get rid of KVO, and observe an object in pure Swift. – CocoaUser Dec 03 '20 at 07:05
  • 2
    But you don't need to observe anything, let alone KVO. You just need a [computed property](https://docs.swift.org/swift-book/LanguageGuide/Properties.html#ID259). – Sweeper Dec 03 '20 at 07:07
  • @Sweeper thanks. I just looking for a good way and practice in swift. the delta.value is related to UI. – CocoaUser Dec 03 '20 at 07:13

1 Answers1

2

Well, The only way to solve your problem, in my opinion, is to use Value observing in swift. For example:

var delta = Delta() {
    didSet {
        // Do all required operation& You can use delta value which already has updated value
    }
}

Try it, maybe it will help you

UPD: one way to solve your problem

struct Component {
    var value = 0
}

struct Delta {
    var a: Component {
        didSet {
            updateDelta()
        }
    }
    var b: Component {
        didSet {
            updateDelta()
        }
    }
    var value = 0       //  equation: a.value - b.value
    
    init(a: Component, b: Component) {
        self.a = a
        self.b = b
    }
    
    private mutating func updateDelta() {
        self.value = a.value - b.value
    }
}
Dmitry Kuleshov
  • 571
  • 4
  • 12
  • Please povide an example where "When I update delta.a.value or delta.b.value that will auto calculate delta.value". – Willeke Dec 04 '20 at 09:55