func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if let getimURL = newslists[indexPath.section][indexPath.row].imageURL as String?{
if getimURL != "None"{
return 230.0
}; return 70.0
}else{
return 70.0
}
}
当我的连接不良时,该错误经常出现,可能导致 newslists
数组填充太慢,
无论如何,索引越界错误指的是该行
如果让 getimURL = newslists[indexPath.section][indexPath.row].imageURL 作为字符串?{
我的问题是,如果这一行有问题,程序不应该运行 else
括号之间的代码吗?
这不是条件声明的目的吗?
如果没有,我该如何防止这个错误?
最佳答案
if let
声明的目的是解开 String?
可选值。错误是在访问数组时,您假设 newslists[indexPath.section][indexPath.row] 存在而不是检查它。尝试类似的东西
if newslists.count > indexPath.section {
if newslists[indexPath.section].count > indexPath.row {
if let getimURL = newslists[indexPath.section][indexPath.row].imageURL as? String {
if getimURL != "None"{
return 230.0
}
}
}
}
return 70.0
此外,您对于连接不良是一个问题的看法是正确的。如果这是您的数据源,并且它依赖于网络请求(在后台线程上执行)的信息,则无法保证调用此方法时将填充数据源。
关于ios - 条件声明 Swift 上的数组索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31410514/