简体   繁体   English

转义闭包捕获变异的“self”参数

[英]Escaping closure captures mutating 'self' parameter

I'm trying to subscribe to an observable generated by a combineLatest , after flatMap .我正在尝试订阅由combineLatest生成的combineLatest ,在flatMap之后。 If I'm running this code in a struct I get this error:如果我在结构中运行此代码,则会收到此错误:

Escaping closure captures mutating 'self' parameter

If I change to a class the error does not occurs.如果我更改为类,则不会发生错误。 I understand that with struct I cannot asynchronously mutate the state of the struct, but, in this case I'm actually not mutating it, or am I?我知道使用 struct 我不能异步改变结构的状态,但是,在这种情况下,我实际上并没有改变它,还是我?

There's another way to fix it without using a class?还有另一种方法可以在不使用类的情况下修复它吗?

public struct ViewModel {

    let disposeBag = DisposeBag()
    var relay1: PublishRelay<()>
    var relay2: PublishRelay<()>

    init() {
        relay1 = PublishRelay<()>()
        relay2 = PublishRelay<()>()

        Observable.combineLatest(relay1, relay2)
            .filter { tuple in 1 == 1 } // some boolean logic here
            .flatMap { _ in return Observable<Void>.just(()) } // some map filter here
            .subscribe(onNext: { _ in
                self.doCoolStuff()
            }).disposed(by: disposeBag)
    }

    func doCoolStuff() {
        // Do cool Stuff here
    }
}

All instances methods receive a reference to self as an implicit first parameter, which is why you have to capture self to call the instance method.所有实例方法都接收对 self 的引用作为隐式第一个参数,这就是为什么您必须捕获 self 以调用实例方法。 Is you don't actually need any instance variables then make doCoolStuff() a static function and you will no longer need to call it with self.您实际上不需要任何实例变量,然后使doCoolStuff()成为static函数,您将不再需要使用self. (you can use Self. as of Swift 5, or just the type name ViewModel. ). (从 Swift 5 开始,您可以使用Self. ,或者仅使用类型名称ViewModel. )。 You can similarly avoid this issue if doCoolStuff is a closure defined inside of init.如果doCoolStuff是在 init 中定义的闭包,您同样可以避免这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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