Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift, check if array has value at index

Tags:

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

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?

like image 771
UpCat Avatar asked Nov 10 '14 10:11

UpCat


1 Answers

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

like image 105
Antonio Avatar answered Nov 02 '22 20:11

Antonio