是否可以在Swift中为类定义setter

c0vxltue  于 2022-12-17  发布在  Swift
关注(0)|答案(1)|浏览(116)

我创建了一个CurrentValueSubject的版本,它不能像@Published那样完成。但是,我想删除对.send(value)的需求,并为这个类定义一个setter来执行它。这可能吗?
所以从这个:

customPublisher.send(newValue)

改为:

customPublisher = newValue
final class CustomPublisher<Output: Any>: Publisher {
    typealias Failure = Never

    var value: Output
    private var wrapper: CurrentValueSubject<Output, Failure>

    init(_ value: Output) {
        self.value = value
        wrapper = .init(value)
    }

    func send(_ value: Output) {
        self.value = value
        wrapper.send(value)
    }

    func send(subscription: Subscription) {
        wrapper.send(subscription: subscription)
    }

    func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
        wrapper.receive(subscriber: subscriber)
    }
}
tyu7yeag

tyu7yeag1#

不能使用语法customPublisher = newValue来发布新值,因为在该语法中,您将一个(可能是全新的)发布者放入customPublisher中。
不过,你可以像CurrentValueSubject一样使customPublisher.value = newValue工作,你需要用setter使value成为一个计算属性,如下所示:

import Combine

final class CustomPublisher<Output: Any>: Publisher {
    private var wrapped: CurrentValueSubject<Output, Failure>

    typealias Failure = Never

    var value: Output {
        get { wrapped.value }
        set { wrapped.value = newValue }
    }

    init(_ value: Output) {
        wrapped = .init(value)
    }

    func send(_ value: Output) {
        wrapped.send(value)
    }

    func send(subscription: Subscription) {
        wrapped.send(subscription: subscription)
    }

    func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
        wrapped.receive(subscriber: subscriber)
    }
}

相关问题