我试图遍历Swift中的一系列ViewController,但是不幸的是我遇到了我不理解的编译错误。这是我的相关代码:
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)
但是,我不断收到来自Xcode的错误消息,要求我在for循环语句中插入“,”作为分隔符。有人可以看到我在做什么错吗?
而不是使用数字for循环,为什么不在语法中使用for ...?
if let navController = self.navigationController {
for aVC in navController.viewControllers {
if aVC..isKindOfClass(MyViewController) {
navController.popToViewController(aVC, animated: true)
break
}
}
}
我使用了可选的绑定将折叠self.navigationController?
到navController中,并在语法上使用...。
另外,我认为您无需将视图控制器转换为您的MyViewController
类,因为您所要做的全部就是将其发送到popToViewController函数,该函数需要ANY UIViewController
。
如果需要数组中各项的索引,则可以使用enumerate
数组中的函数,该函数返回一组元组:
for (index, aVC) in navController.viewControllers.enumerate() {
//Do stuff
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句