Henry Brown
Henry Brown

Reputation: 2237

Adding a break or continue statement for a for in loop

I have a for in loop which iterates through a number of objects, when it finds a certain value inside the loop I want a popUpViewController to pop up and show some information, then once the user has dismissed the popUpViewController, I then want the iteration to continue and if it again finds another value to pop up again , and so on and so forth until the iteration has finished, this is my code and where I am up to, but I'm not sure how to do it. code:

var popUpViewController = PopUpViewControllerSwift(
var results = [1,2,3,1,2,3,1,2,3]

for result in results {
    if result == 2 {
       self.view.addSubview(self.popUpViewController.view)
       self.addChildViewController(self.popUpViewController)
       self.popUpViewController.setValues(UIImage(named: "Me.png"), messageText: "You have matched with \(usernameOne)!", congratsText: "Snap!")
       self.popUpViewController.didMoveToParentViewController(self)
    }
}

This has been simplified down to get to the point.

Upvotes: 2

Views: 659

Answers (1)

GoZoner
GoZoner

Reputation: 70165

Upon dismissal of your PopUpViewControllerSwift you are going to need to continue on with the computation from the last index. [You'll need a way to recognize when the popup controller has been dismissed - there are numerous ways to do this in UIKit depending on your specific design. For example, in viewDidDisappear()]. To continue from the last index, define a function that takes that index, does the match, and then recursively calls itself with index + 1 to continue on.

let processFrom : ((index:Int) -> Void)!
processFrom     = {(index:Int) -> Void) in
  if index < results.count {
    let result = results[index]

    if result == 2 {
       // setup view

       // provide the continuation - assumes `onDismiss` is defined
       // as a closure to be used when the view is dismissed.
       self.popupViewController.onDismiss = { processFrom (index + 1) }
    }
    else { processFrom (index + 1) }
  }
}

This processFrom captures the results variable and repeatedly processes element from the results based on the provided index.

Note: Swift isn't very swift regarding recursive functions; hence the use of processFrom as a implicitly unwrapped optional. Depending on your code, if processFrom is a function in a class/struct, then you'll avoid this style just by using func.

Upvotes: 1

Related Questions