ios - SwiftUI 转义闭包捕获变异的 'self' 参数

标签 ios swift xcode swiftui

我有一个可以通过两种方式打开的 View 。一个带有提供给它的数据,另一个带有对 Firestore 文档的文档引用。我创建了两个构造函数,第一个提供数据,另一个提供文档引用。
然后我使用这个引用进行网络调用位我收到一个错误:
Escaping closure captures mutating 'self' parameter
关于如何解决这个问题的任何想法?

@State var request: RequestModel?

init(request: RequestModel) {
    self.request = request
}

init(reference: DocumentReference) {
    FirestoreService().fetchDocument(documentReference: reference) { (request: RequestModel) in
        self.request = request
    }
}

最佳答案

很抱歉,上面的答案是错误的。

An object's initializer cannot do anything asynchronous. Its job is to produce the object immediately, with all its properties initialized


--> 这是绝对错误的。
10 年来,我在 Objective-C/C/Swift 中成功完成了大量的多线程编程:没有任何内存泄漏、数据访问或访问竞争。
我已经成功地让一些对象在制作我的游戏时异步初始化,尤其是。当我需要以高性能方式初始化尽可能多的对象以及许多惰性对象时。
初始化器可以做异步,但这里的问题是 'self' 在下面的转义闭包中无法修改。
init(reference: DocumentReference) {
    FirestoreService().fetchDocument(documentReference: reference) {    
        (request: RequestModel) in
         self.request = request
}
初始化器中的闭包详细信息是
{        
    @escaping [unowned self] (request: RequestModel) in

        self.request = request
}
因此,闭包中的“自我”将比函数生命周期更长。
上面的代码似乎是 View 类型的一部分,创建为结构。
来自 https://docs.swift.org/swift-book/LanguageGuide/Closures.html ,

"If self is an instance of a structure or an enumeration, you can always refer to self implicitly. However, an escaping closure can’t capture a mutable reference to self when self is an instance of a structure or an enumeration. Structures and enumerations don’t allow shared mutability, as discussed in Structures and Enumerations Are Value Types."


因此,“自我”不能是可变的。
这就是您的代码收到错误消息的原因:“转义闭包捕获变异的'self'参数”。
一个更好的解决方案是将部件移动到修饰符内的另一个位置,如“didAppear()”。
因为提问者在这里没有提供更多他或她的代码。
我无法在这里提供更具体的答案。

关于ios - SwiftUI 转义闭包捕获变异的 'self' 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60698792/

相关文章:

iphone - 自定义字典实现 : Can I Create My Custom affix file?

ios - swift 警告 : Application delegate received call to -application:performFetchWithCompletionHandler: but the completion handler was never called

swift - 以编程方式创建 TabBar 但不在 rootViewController 上

ios - UITextView 打字时无法控制地弹起

ios - 我如何作为团队成员提交 TestFlight 构建

Xcode 4.0.1 "Don' 没有权限查看“旧项目文件 - 帮助!

cocoa - 有没有办法无限期地暂停 NSTHread 并从另一个线程恢复它?

ios - Flutter:在iOS版本的YouTube应用中打开视频

swift - 重置 UIStepper 的值

objective-c - 不能继承 UIColor 吗?