gpt4 book ai didi

swift - Swift 5 : What's 'Escaping closure captures mutating ' self' parameter' and how to fix it

转载 作者:行者123 更新时间:2023-12-03 17:47:33 41 4
gpt4 key购买 nike

大家好,我正在尝试制作一个简单且可重复使用的Swift网络层

也许这不是在 View 中循环返回数据的最佳方法,但是在尝试将返回的Api数据循环到SwiftUI View 中后,我遇到了错误:

Escaping closure captures mutating 'self' parameter

而且不知道我在本课中错过了什么

这是文件的图片

enter image description here

ContentView.swift
struct ContentView: View {

var emptyDataArr: [CollectionItem] = []

init() {
ServiceLayer.request(router: Router.getSources) { (result: Result<[String : [CollectionItem]], Error>) in
switch result {
case .success(let data):
print(data)
self.emptyDataArr = data["custom_collections"]!

case .failure:
print(result)
}
}
}

var body: some View {
VStack (alignment: .leading) {
Text("No thing yet")
}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

ServiceLayer类 ServiceLayer.swift
class ServiceLayer {
// 1.
class func request<T: Codable>(router: Router, completion: @escaping (Result<[String: [T]], Error>) -> ()) {
// 2.
var components = URLComponents()
components.scheme = router.scheme
components.host = router.host
components.path = router.path
components.queryItems = router.parameters
// 3.
guard let url = components.url else { return }
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = router.method
// 4.
let session = URLSession(configuration: .default)
let dataTask = session.dataTask(with: urlRequest) { data, response, error in
// 5.
guard error == nil else {
completion(.failure(error!))
print(error?.localizedDescription)
return
}
guard response != nil else {
return
}
guard let data = data else {
return
}
print(data)
// 6.
let responseObject = try! JSONDecoder().decode([String: [T]].self, from: data)
// 7.
DispatchQueue.main.async {
// 8.
completion(.success(responseObject))
}
}
dataTask.resume()
}
}

最佳答案

问题在于ContentView是一个结构,这意味着它是一个值类型。您不能将其传递给闭包并对其进行突变。如果您这样做,则不会有任何改变,因为闭包将具有其自己的结构独立副本。

您的问题是您将 View 和模型混合在一起。给定View可以有很多很多副本(每次将其传递给函数时,都会创建一个副本)。您不希望所有这些副本都发起一个请求。取而代之的是将此请求逻辑移到Model对象中,然后让View对其进行观察。

关于swift - Swift 5 : What's 'Escaping closure captures mutating ' self' parameter' and how to fix it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58327013/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com