Quintana Quintana - 2 years ago 51
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

). 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 {

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
clause would naturally introduce an optional, since if the arithmetic works out wrong then there is no matching value of

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

Answer Source

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 {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download