[英]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.这意味着您的
userInfo
、 isLogin
等将是@Published
属性并且可能需要是可选项,因为在getActivity
完成之前它们不会有值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.