Swift,如何检查数组中是否存在指定索引的值

5
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个回答

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)
}

我建议您再次阅读有关可选项的内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接