零检查后发现无

时间:2015-12-14 13:00:33

标签: swift

即使我在使用该值之前检查nil,我也会收到意外发现的nil错误。我在这里错过了什么吗?

if self.orders[indexPath.row]["distanceToHouseHold"] != nil {
    cell.distanceTextField.text = "\(self.orders[indexPath.row]["distanceToHouseHold"] as! String)m"
}

错误在第二行当然。

4 个答案:

答案 0 :(得分:6)

可能distanceToHouseHold不是字符串,并且在类型转换时失败。尝试使用if-let检查或新的guard检查。

if let distance = self.orders[indexPath.row]["distanceToHouseHold"] as? String {
    cell.distanceTextField.text = "\(distance)m"
}

答案 1 :(得分:2)

请改为:

if let distance self.orders[indexPath.row]["distanceToHouseHold"] as? String {
    cell.distanceTextField.text = distance + "m"
}

这将检查它不是n并且转换为字符串

答案 2 :(得分:0)

使用guard let

guard let whatever = self.orders[indexPath.row]["distanceToHouseHold"] as? String else  {
  return 
} 
    cell.distanceTextField.text = whatever + "m"
}

如果不能正常工作,请尝试:

guard let whatever = self.orders[indexPath.row]["distanceToHouseHold"] else  {
      return 
    } 
        cell.distanceTextField.text = String(whatever) + "m"
}

答案 3 :(得分:0)

试试这个:

let whatValue = self.orders[indexPath.row]["distanceToHouseHold"]
println(" value is \(whatValue)");

这将帮助您查看输出内容。之后你可以决定出了什么问题。

干杯!!