[swift] Swift中”[AnyObject]?does not have a member named generator”处理

[复制链接]
查看918 | 回复0 | 2015-7-12 10:30:24 | 显示全部楼层 |阅读模式
1435804700243088.jpg 7 x; _* A7 c6 z' c- j9 J# I2 U
  有个小需求,需要遍历当前导航控制器栈的所有ViewController。UINavigationController类自身的viewControllers属性返回的是一个[AnyObject]!数组,不过由于我的导航控制器本身有可能是nil,所以我获取到的ViewController数组如下:) N& O: J) b7 C1 Z
var myViewControllers: [AnyObject]? = navigationController?.viewControllers. K/ I  `) L  U: O4 C+ b
  获取到的myViewControllers是一个[AnyObject]?可选类型,这时如果我直接去遍历myViewControllers,如下代码所示for controller in myViewControllers {3 X. P# {* V$ J/ t- d/ H. C0 N
    ...
" i& |9 z8 W0 N0 I}: m* C- d) c" {
  编译器会报错,提示如下:[AnyObject]? does not have a member named "Generator"7 _, C1 i4 W' |
  实际上,不管是[AnyObject]?还是其它的诸如[String]?类型,都会报这个错。其原因是可选类型只是个容器,它与其所包装的值是不同的类型,也就是说[AnyObject]是一个数组类型,但[AnyObject]?并不是数组类型。我们可以迭代一个数组,但不是迭代一个非集合类型。4 Y/ W# f  p* R5 T& B
  在stackoverflow上有这样一个有趣的比方,我犯懒就直接贴出来了:
) J! d0 u" }8 w$ M: x9 {5 j  x  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.: ~" o$ m- j% D- t0 O" V
  所有,这里的处理应该是:if let controllers = myViewControllers {; O- e* w! K, s+ P# g2 G
    for controller in controllers {+ [0 `( R- ~* d6 K" g6 K$ `
        ......9 Z" m3 |6 l/ d4 _
    }/ p2 x3 ~; t4 F" {! S! y
}
+ G4 @  B) V! Y- S  [color=rgb(0,]参考5 t* @+ y$ E7 J5 ]& H6 @0 d3 V

" N% g3 f0 Y8 K9 m+ k  Loop through [AnyObject]? results in does not have a member named generator
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则