Quintana Quintana - 6 months ago 11
iOS Question

Using "where" clauses to produce optional types in Swift arithmetic

I would like to trigger conditional logic based around certain UI relationships during user interaction (in this case, I want to call a method when a user scrolls to a certain point in a

UIScrollView
). I would expect the following line of code to do this legally, since it is quite expressive:

func scrollViewDidScroll(scrollView: UIScrollView) {
guard let overlap = scrollView.contentOffset.y - 220 where overlap > 0 else {
return
}

reactToScrollOverlap(of: overlap)
}


However, I get the error that the
guard let
requires an optional type. That's reasonable, but I expected in this case that the
where
clause would naturally introduce an optional, since if the arithmetic works out wrong then there is no matching value of
overlap
.

Is there a way to use
guard let
(or, alternatively,
if let
) such that included
where
clauses stipulate conditions on the outcomes of arithmetic between Int, CGFloat, or other primitive/primitive-like types?

JAL JAL
Answer

guard and if let statements are normally only used to unwrap optionals. I'm not really thrilled with this solution, but you could cast scrollView.contentOffset.y as an Optional<CGFloat> to get the behavior you want:

guard let overlap = scrollView.contentOffset.y - 220 as CGFloat? where overlap > 0 else {
    return
}