【发布时间】:2016-03-30 06:33:34
【问题描述】:
根据我对 swift 中guard 语句的理解,我正在执行以下操作:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let identifier = "identifier"
let dequeCell = tableView.dequeueReusableCellWithIdentifier(identifier)
guard let cell = dequeCell else
{
// The following line gives error saying: Variable declared in 'guard'condition is not usable in its body
cell = UITableViewCell(style: .Default, reuseIdentifier: identifier)
}
cell.textLabel?.text = "\(indexPath.row)"
return cell
}
我只是想了解我们可以在guard 语句中创建一个变量并在函数的其余部分访问它吗?还是保护语句旨在立即返回或抛出异常?
或者我完全误解了guard语句的用法?
【问题讨论】:
-
否
guard语句应该导致方法返回或如果为假则抛出。 -
使用较新的
dequeue...方法(期望索引路径作为第二个参数的方法):如果重用池中没有可用的单元格,它将为您分配单元格,并且永远不会返回 @987654327 @。然后,强制转换为您的自定义单元子类(如果您正确注册了类/标识符,这将永远不会失败)。