I have the following code below:
var rootTasks: [Task]?
func loadRootTasks() {
rootTasks == nil ? rootTasks = [Task]() : rootTasks?.removeAll() // removeAll() works here
TasksManager.loadTasks(parentTaskIDString: "0", tasks: &rootTasks!)
}
static func loadTasks(parentTaskIDString: String, tasks: inout [Task]) {
let urlString = Config.httpsProtocol + "://" + Config.server + Config.portString + "/" + TasksManager.getTasksEndpoint + "/" + parentTaskIDString
let url = URL(string: urlString)
var urlRequest = URLRequest(url: url!)
urlRequest.setValue(AccountsManager.sharedInstance.securityAccessToken, forHTTPHeaderField: "Authorization")
let defaultSession = URLSession(configuration: .default)
let getTasksTask = defaultSession.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
print("GetTasks response status code != 200")
return
}
guard error == nil else {
print("GetTasks error")
return
}
guard let jsonData = data else {
print("GetTasks did not receive JSON data")
return
}
do {
// PROBLEM is here:
// compiler flags "Escaping closures can only capture inout parameters explicitly by value"
tasks.removeAll() // removeAll() does not work here
// same error here
tasks = try JSONDecoder().decode([Task].self, from: jsonData)
NotificationCenter.default.post(name: .rootTasksRefreshed, object: nil, userInfo: nil)
}
catch {
print("GetTasks JSON parsing exception")
}
})
getTasksTask.resume()
}
The problem is in the line "// PROBLEM ...". The compiler flags the "Escaping closures can only capture inout parameters explicitly by value" error.
The function "loadTasks" is a static method, which is called by "loadRootTasks". It needs to pass a "tasks" array which is a member variable, and needs to be modified from within the static method after the asynchronous method dataTask() runs.
How do I resolve the problems to be able to "tasks.removeAll()", etc?
I have read other posts, but there are not for Swift 4.2. I need help specifically for Swift 4.2. Thanks!