Swift,检查数组是否在索引处有值

时间:2014-11-10 10:13:15

标签: ios swift nsarray

var cellHeights: [CGFloat] = [CGFloat]()

if let height = self.cellHeights[index] as? CGFloat {
    self.cellHeights[index] = cell.frame.size.height
} else {
    self.cellHeights.append(cell.frame.size.height)
}

我需要检查指定索引处的元素是否存在。但是上面的代码不起作用,我得到了构建错误:

  

从CGFloat到CGFloat的条件性转发总是成功

我也尝试过:

if let height = self.cellHeights[index] {}

但这也失败了:

Bound value in a conditional binding must be of Optional type

任何想法都错了吗?

1 个答案:

答案 0 :(得分:8)

cellHeights是一个包含非可选CGFloat的数组。所以它的任何元素都不能为nil,因此如果索引存在,那个索引上的元素就是CGFloat

您尝试做的事情只有在您创建选项数组时才有可能:

var cellHeights: [CGFloat?] = [CGFloat?]()

在这种情况下,可选的绑定应按如下方式使用:

if let height = cellHeights[index] {
    cellHeights[index] = cell.frame.size.height
} else {
    cellHeights.append(cell.frame.size.height)
}

我建议您再次阅读Optionals

相关问题