简体   繁体   中英

How to create MutableProperty<T> from MutableProperty<U> in Swift ReactiveCocoa 4

Is there any easy way to create MutableProperty from MutableProperty in Swift ReactiveCocoa 4?

I have a case that, and I want an way to create classB with classA, in which I need to setup statusB with statusA, but how to do this?

class ClassA {
  var statusA = MutableProperty<T>
}

class ClassB {
    var statusB = MutableProperty<U>

    func getStatusB(from StatusA: T) -> U {
        // .. assume this is implemented.
    }

    init(statusB: U) {
        //...
    }

    convenience init(from classA: ClassA) {
        self.statusB = // here how to setup this value from classA's statusA with getStatusB(from:)?
    }
}

you can't make a MutableProperty<U> directly from a MutableProperty<T> but you can make a MutableProperty<U> with initial value getStatusB(from: classA.statusA.value) and then bind it to classA.statusA.signal.map(getStatusB) so all changes to the MutableProperty<T> propagate to the MutableProperty<U> , like

convenience init(from classA: ClassA) {
    self.init(getStatusB(from: classA.statusA.value)))
    self.statusB <~ classA.statusA.signal.map(getStatusB)
}

(however for this to compile, getStatusB can't be an instance method of ClassB because you need to be able to call it before you call self.init )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM