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

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?

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.