我试图在我用来处理来电的功能中创建一个循环,但我收到错误"无法分配到属性:' item'是一个“让...”恒定"
func didReceiveResponse(response:NearbyCars?, error : Error?) -> Void {
dount += 1
if let error = error {
let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
let actionDismiss = UIAlertAction(title: "Dismiss", style: .cancel, handler: nil)
let actionRetry = UIAlertAction(title: "Retry", style: .default, handler: { (action) in
DispatchQueue.main.async {
self.loadPlaces(true)
}
})
alertController.addAction(actionRetry)
alertController.addAction(actionDismiss)
DispatchQueue.main.async {
self.present(viewController: alertController)
}
}
if let response = response {
self.response = response
if response.status == "OK" {
if let carsDownloaded = response.cars {
var number = numberCars / (categories?.count)!
let quotient = numberCars / (categories?.count)!
let remainder = numberCars % (categories?.count)!
for item in (categories?.enumerated())! {
item.element?.availability = quotient + (item.offset < remainder ? 1 : 0)
} // HERE THE ERROR
cars.append(contentsOf: carsDownloaded.prefix(number))
if dount == numberCars { return }
sortedArray = cars.sorted {
distance(from: currentLocation!, to: $0.location!) < distance(from: currentLocation!, to: $1.location!)
}
}
self.tableView?.reloadData()
} else {
let alert = UIAlertController.init(title: "Error", message: response.status, preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction.init(title: "Retry", style: .default, handler: { (action) in
DispatchQueue.main.async {
self.loadPlaces(true)
}
}))
self.present(viewController: alert)
}
isLoading = false
} else {
print("response is nil")
}
}
此行item.element?.availability = quotient + (item.offset < remainder ? 1 : 0)
,而我正在尝试创建一个循环,将numberCars / (categories?.count)!
的其余部分分配给类别(因为现在var number = numberCars / (categories?.count)!
仅在没有休息时工作)。我该如何解决?
答案 0 :(得分:1)
您可以在一个范围内执行循环,然后通过索引访问categories
以获取可变对象:
for i in 0..<(categories?.count)! {
var item = categories[i]
item.element?.availability = quotient + (item.offset < remainder ? 1 : 0)
}
我还建议通过围绕categories
守护来避免使用强行展开:
guard let categories = categories else {
//Handle a nil categories array here
return
}