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

查看1175 | 回复0 | 2015-7-12 10:30:24 | 显示全部楼层 |阅读模式
1435804700243088.jpg 0 n' @1 A- p; g8 l0 F: c
  有个小需求,需要遍历当前导航控制器栈的所有ViewController。UINavigationController类自身的viewControllers属性返回的是一个[AnyObject]!数组,不过由于我的导航控制器本身有可能是nil,所以我获取到的ViewController数组如下:) e9 U0 j% e+ E; R
var myViewControllers: [AnyObject]? = navigationController?.viewControllers8 r$ p( S! C# w1 G
  获取到的myViewControllers是一个[AnyObject]?可选类型,这时如果我直接去遍历myViewControllers,如下代码所示for controller in myViewControllers {7 H. L; G' q5 F. w8 B# ~' L
$ D# B, t: N5 D9 ?}
# K! m$ a! l1 @# N4 N$ l  编译器会报错,提示如下:[AnyObject]? does not have a member named "Generator"
7 ~- D/ t9 l* ^1 B' k6 {  实际上,不管是[AnyObject]?还是其它的诸如[String]?类型,都会报这个错。其原因是可选类型只是个容器,它与其所包装的值是不同的类型,也就是说[AnyObject]是一个数组类型,但[AnyObject]?并不是数组类型。我们可以迭代一个数组,但不是迭代一个非集合类型。$ ^. D1 P' e. w& Y0 r9 I5 K' e
& n, {( p1 ~3 _7 v) d  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.3 F+ ]1 s7 l( ?2 U" u
  所有,这里的处理应该是:if let controllers = myViewControllers {, K. i+ }7 j) J9 u7 V
    for controller in controllers {
: a5 C" m: S3 V( O5 L        ......
: x9 X% _" @% Z2 v: @    }. ?3 @+ H1 a& t& r
6 b; S- s7 S& m3 D5 ?  [color=rgb(0,]参考! a  ^# w* k4 s4 L7 D. r% C& x

; z* A# g2 Y+ K  Loop through [AnyObject]? results in does not have a member named generator

使用道具 举报

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