Swift, check if the array has index value

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 if an element exists at the specified index. However, the above code does not work, I get a build error:

Conditional downgrade from CGFloat to CGFloat is always executed

I also tried:

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

but this also failed:

 Bound value in a conditional binding must be of Optional type 

Any ideas on something wrong?

+5
source share
1 answer

cellHeights is an array containing optional CGFloat . Thus, any of its elements cannot be nil, as such, if an index exists, the element of this index is CGFloat .

What you are trying to do is what is possible only if you create an array of options :

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

and in this 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 read Options again

+8
source

Source: https://habr.com/ru/post/1206554/


All Articles