Reputation: 70466
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)
}
I need to check whether an element at a specified index exists. However the above code does not work, I get the build error:
Conditional downcast from CGFloat to CGFloat always succeeds
I also tried with:
if let height = self.cellHeights[index] {}
but this also failed:
Bound value in a conditional binding must be of Optional type
Any ideas whats wrong?
Upvotes: 5
Views: 7832
Reputation: 72810
cellHeights
is an array containing non-optional CGFloat
. So any of its elements cannot be nil, as such if the index exists, the element on that index is a CGFloat
.
What you are trying to do is something that is possible only if you create an array of optionals:
var cellHeights: [CGFloat?] = [CGFloat?]()
and in that case the optional binding should be used as follows:
if let height = cellHeights[index] {
cellHeights[index] = cell.frame.size.height
} else {
cellHeights.append(cell.frame.size.height)
}
I suggest you to read again about Optionals
Upvotes: 8