简体   繁体   English

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

[英]Swift ui Escaping closure captures mutating 'self' parameter

I am having the following problem when used in init() , can anyone help me out?我在init()使用时遇到以下问题,有人可以帮我吗?

在此处输入图片说明

    @State private var activity: [ResponseActivity] = [ResponseActivity()]

    func getActivity(completion: @escaping ([ResponseActivity]?) -> ()){
        var userInfo: [ResponseActivity] = [ResponseActivity()]
        let url = URL(string: "https://api.github.com/users/\(self.userInfo.login)/received_events")!
        let urlRequest = URLRequest(url: url)
        
        print("self.userInfo.login", self.userInfo.login)
        
        let task = URLSession.shared.dataTask(with: urlRequest) { data, urlResponse, error in
            guard let content = data else {
                print("Error getting data from API.")
                return
            }
            
            do {
                userInfo = try JSONDecoder().decode([ResponseActivity].self, from: content)
            } catch {
                print("Error parsing URL from data Activity.")
                return
            }
            completion(userInfo)
        }
        task.resume()
    }

Properties in a struct like this ( View ) are immutable.像这样的struct ( View ) 中的属性是不可变的。 You can set initial values inside init , but then they aren't mutable later.您可以在init设置初始值,但之后它们将不可变。 Special property wrappers like @State let you mutate values later on, but you're attempting to set the actual value on the struct by using _activity = State(...) .@State这样的特殊属性包装器允许您稍后@State值,但您正在尝试使用_activity = State(...)struct上设置实际值。

I'd suggest moving asynchronous code like this to an ObservableObject -- then, you'll have a class with mutable properties.我建议将这样的异步代码移动到ObservableObject ——然后,您将拥有一个具有可变属性的class This will mean that your userInfo , isLogin , etc will be @Published properties and will probably need to be optionals, since they won't have values until getActivity completes.这意味着您的userInfoisLogin等将是@Published属性并且可能需要是可选项,因为在getActivity完成之前它们不会有值。

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

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