標籤:
開發中常見錯誤和警告總結(八)Swift中”[AnyObject]?does not have a member named generator”處理
有個小需求,需要遍曆當前置航控制器棧的所有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 { ...... }}
ios開發——錯誤總結篇&開發中常見錯誤和警告總結(八)