2014-11-05 36 views
6

我是新來的swift,但我想我得到它的一個竅門。雖然這很難阻止我的進步。self.navigationController?.popViewControllerAnimated來自UIAlertController

我想要做的是當我們找不到相關數據到他的查詢時,向用戶拋出錯誤消息,然後繼續將他帶回到先前的ViewController。

但是,我很難做到這一點。在添加動作的行上,我收到以下錯誤:'UIViewController?'不是Void的亞型

let alertController = UIAlertController(title: "Oops", message: "We couldn't find any data for this title, sorry!", preferredStyle: UIAlertControllerStyle.Alert) 

alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in 
    self.navigationController?.popViewControllerAnimated(true) 
})) 

我該怎麼做?我錯過了明顯的東西嗎?我試圖搞亂棄用的UIAlertView,但沒有成爲更聰明的人。

回答

23

在封閉體只需添加一個明確的return聲明:

alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in 
    self.navigationController?.popViewControllerAnimated(true) 
    return 
})) 

爲什麼出現這種情況是單個語句關閉作爲返回值進行處理,所以編譯器使用的popViewControllerAnimated返回值的原因,毫不意外的是UIViewController?。顯式返回語句避免了這一點。

此行爲記錄在Implicit Returns from Single-Expression Closures

+0

感謝您的快速回復!由於最短的時間,我甚至無法將您的答案標記爲正確。 – 2014-11-05 16:26:45

相關問題