ios開發——錯誤總結篇&開發中常見錯誤和警告總結(八)

來源:互聯網
上載者:User

標籤:

開發中常見錯誤和警告總結(八)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開發——錯誤總結篇&開發中常見錯誤和警告總結(八)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.