syedfa syedfa - 3 months ago 7
Swift Question

Having issue with for-loop in Swift

I am trying to iterate over an array of ViewControllers in Swift, but unfortunately I am getting compilation errors that I don't understand. Here is my relevant code:

let alertController = UIAlertController(title: "Error", message: "You have an error.", preferredStyle: .Alert)

let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
print("you have pressed OK button");
//below is my loop causing me trouble
for (i in 0..< self.navigationController?.viewControllers.count) {
if (self.navigationController?.viewControllers[i].isKindOfClass(MyViewController) == true) {
self.navigationController?.popToViewController(self.navigationController!.viewControllers[i] as! MyViewController, animated: true)

break;
}
}
}
alertController.addAction(OKAction)

self.presentViewController(alertController, animated: true, completion:nil)


However, I keep getting errors from Xcode asking me to insert "," as a separator in my for loop statement. Can anyone see what it is I'm doing wrong?

Answer

Just remove the brackets from your for loop and add proper spacing between 0 and self:-

for i in 0 ..< self.navigationController?.viewControllers.count {
                    if(self.navigationController?.viewControllers[i].isKindOfClass(MyViewController) == true) {

                        self.navigationController?.popToViewController(self.navigationController!.viewControllers[i] as! MyViewController, animated: true)

                        break;
                    }
                }
Comments