Chapter 7 p109 Continue in loop

Hi there,

I’m working through iOS Animations and came across this problem. In chapter 7, working in actionToggleMenu:

@IBAction func actionToggleMenu(_ sender: AnyObject) {
    titleLabel.superview?.constraints.forEach { constraint in
        print(" -> \(constraint.description)")
    }
    isMenuOpen = !isMenuOpen
    titleLabel.superview?.constraints.forEach { constraint in
        if constraint.firstItem === titleLabel && constraint.firstAttribute == .centerX {
            constraint.constant = isMenuOpen ? -100.0 : 0.0
            return
        }
        if constraint.identifier == "TitleCenterY" {
            constraint.isActive = false
            continue
        }
    }

In second if-statement of the for-loop, the section that checks if the identifier of the constraint is TitleCenterY, we type continue. However Xcode throws an error and complains that continue only works inside a loop:

'continue' is only allowed inside a loop.

I removed continue and the code works, and so I’m wondering what deal is here.

Thanks!

foreach isn’t a for-loop. It’s iterating through every element of the collection of constraints, but the scope (beginning { constraint in is a closure which gets called on each element.

You can end a closure early using return, but you can’t use continue or break; foreach doesn’t give you any way to end the loop early.

1 Like