标签:
有个小需求,需要遍历当前导航控制器栈的所有ViewController。UINavigationController类自身的viewControllers属性返回的是一个[AnyObject]!数组,不过由于我的导航控制器本身有可能是nil,所以我获取到的ViewController数组如下:
var myViewControllers: [AnyObject]? = navigationController?.viewControllers
获取到的myViewControllers是一个[AnyObject]?可选类型,这时如果我直接去遍历myViewControllers,如下代码所示
for controller in myViewControllers { ... }
编译器会报错,提示如下:
[AnyObject]? does not have a member named "Generator"
实际上,不管是[AnyObject]?还是其它的诸如[String]?类型,都会报这个错。其原因是可选类型只是个容器,它与其所包装的值是不同的类型,也就是说[AnyObject]是一个数组类型,但[AnyObject]?并不是数组类型。我们可以迭代一个数组,但不是迭代一个非集合类型。
在stackoverflow上有这样一个有趣的比方,我犯懒就直接贴出来了:
To understand the difference, let me make a real life example: you buy a new TV on ebay, the package is shipped to you, the first thing you do is to check if the package (the optional) is empty (nil). Once you verify that the TV is inside, you have to unwrap it, and put the box aside. You cannot use the TV while it‘s in the package. Similarly, an optional is a container: it is not the value it contains, and it doesn‘t have the same type. It can be empty, or it can contain a valid value.
所有,这里的处理应该是:
if let controllers = myViewControllers { for controller in controllers { ...... } }
标签:
原文地址:http://www.cnblogs.com/iCocos/p/4761514.html