据我了解,ReactiveCocoa 4的RACSubject等同于Observer类。
我想将一个信号和一个观察者链接在一起,以便该信号发送将映射操作应用于发送给观察者的事件的事件。
在Obj-C中,它看起来像这样:

// ViewModel.h

@interface ViewModel

@property (readonly) RACSubject *someAction; //expects e.g. int values
@property (readonly) RACSignal *someSignal; //sends e.g. string values

@end

// ViewModel.m

//redeclaring the signal and action as readwrite

@implementation

- (id)init {
  _someAction = [RACSubject subject];
  _someSignal = [_someAction map:^id(NSNumber *index) {
     return "Some string based on index passed in";
  }];
}

@end


现在,当有人将值推入someAction时,someSignal将触发一个包含派生值的事件。
如何在Swift中达到相同的效果?

到目前为止,我能够做的是这样的:

public class ViewModel: NSObject {
    public let (internalSignal, someAction) = Signal<Int, NoError>.pipe()
    public var someSignal: Signal<String, NoError> {
        get {
            return self.internalSignal.map({ [unowned self](index: Int) -> String in
                return "Some string value based on \(self.someArray[index])"
            })
        }
    }
    public let someArray = [1, 2, 3, 4, 5]
}


这看起来是一个糟糕的解决方案,因为


internalSignal应该是私有的,但需要声明为公共以便与Signal的管道匹配
因此,即使可以重复使用同一信号,someSignal也会在每次需要时进行计算。也不能声明为let常量。

最佳答案

您可以像在ObjC中一样在init中初始化成员。

public class ViewModel: NSObject {
    private let internalSignal: Signal<Int, NoError>
    public let someAction: Observer<Int, NoError>
    public let someSignal: Signal<String, NoError>

    override init() {
        (internalSignal, someAction) = Signal<Int, NoError>.pipe()
        someSignal = internalSignal.map { index in
            "Some string value based on \(index)"
        }
        super.init()
    }
}




对于someSignal,您还可以使用lazy initialization,它允许成员引用self

public class ViewModel: NSObject {
    private let internalSignal: Signal<Int, NoError>
    public let someAction: Observer<Int, NoError>
    public private(set) lazy var someSignal: Signal<String, NoError> =
        self.internalSignal.map { [unowned self] index in
            "Some string value based on \(self.someArray[index])"
        }

    override init() {
        (internalSignal, someAction) = Signal<Int, NoError>.pipe()
        super.init()
    }
}


与第一段代码不同,lazy-var仅在使用someSignal之前初始化,而不是在ViewModel的初始化时初始化。

另外,由于它是var,Swift允许您使用mutate其值(没有lazy let这样的东西)。我们可以使用private(set)限制权限,但这不会防止您在某处意外写入self.someSignal = ...



另外,您可以将someSignal设置为一个隐式解包的可选内容,然后手动进行初始化:

public class ViewModel: NSObject {
    private let internalSignal: Signal<Int, NoError>
    public let someAction: Observer<Int, NoError>
    public private(set) var someSignal: Signal<String, NoError>!

    override init() {
        (internalSignal, someAction) = Signal<Int, NoError>.pipe()
        super.init()
        someSignal = internalSignal.map { [unowned self] index in
            "Some string value based on \(self.someArray[index])"
        }
    }
}

10-08 06:27