条件声明Swift

时间:2015-07-14 15:10:44

标签: ios swift conditional declaration

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数组填充太慢,

无论如何,索引越界错误是指行

if let getimURL = newslists[indexPath.section][indexPath.row].imageURL as String?{

我的问题是,如果此行存在问题,程序是否应该在else括号之间运行代码?

这不是条件声明的目的吗?

如果没有,我该如何防止此错误?

4 个答案:

答案 0 :(得分:1)

是条件声明的要点,但如何在Swift中完成数组索引。但是,添加自己的功能非常简单:

extension CollectionType where Index : ForwardIndexType, Index : Comparable {
  subscript (safe index: Index) -> Generator.Element? {
    return indices ~= index ? self[index] : nil
  }
}

let jo = [1, 2, 3, 4, 5]

jo[safe: 2] // 3?

(我从here获得)

这里的问题是你现在有一个双选项。要解决这个问题,您需要选择链接:

if let getimURL = newslists[safe: indexPath.section]?[safe: indexPath.row]?.imageURL.flatMap({ $0 as? String }) {

你很高兴去吧!

答案 1 :(得分:1)

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

另外,你认为连接错误是正确的。如果这是您的数据源并且它依赖于依赖于网络请求的信息(在后台线程上执行),则无法保证在调用此方法时将填充数据源。

答案 2 :(得分:0)

numberOfRowsInSectionnumberOfSectionsInTableView委托方法的实施可能无法报告正确的长度。这将导致表视图提供超出数组范围的索引路径。你可能应该为newslists[section].lengthnumberOfRowsInSection返回newslists.length {/ 1}}。

答案 3 :(得分:0)

看起来你无论如何回归70?

if getimURL != "None"{
        return 230.0
    };  return 70.0 //Right here!!


}else{
    return 70.0
}

不应该......?

if getimURL != "None"{
    return 230.0
}else{
    return 70.0
}