2016-03-03 100 views
-5

我對Swift中的類型轉換有點困惑。類型快速鑄造

有一點疑問。 「as?」,「as!」和「as」之間的區別是什麼?只有「as」。 我們可以說「as」與「is」相似。

在此先感謝。

+0

請搜索第一。這已經被多次令人滿意地解釋了。更好的是,學習Swift。 – matt

+0

是的,我搜索了,我得到了答案「as?」並作爲!」但不僅「as」 – Ranbijay

+0

'as'用於保證成功時進行投射(String到NSString,[AnyObject]到NSArray等) – tktsubota

回答

0

'as'關鍵字用於投射。

'爲' 例如:

let calcVC = destinationViewController as CalculatorViewController 

此行連鑄destinationViewController到CalculatorViewController。但是,如果destinationViewController不是CalculatorViewController或其子類,則會崩潰。

爲了防止崩潰,您可以使用「要是讓」與「爲?」 ......

「的?」例如:

if let calcVC = destinationViewController as? CalculatorViewController { 
    // ... write code to execute if destinationViewController is in fact a CalculatorViewController 
} 

你甚至可以檢查之前,你甚至嘗試做「爲」與「是」關鍵字...

「是」例如:

if destinationViewController is CalculatorViewController { 
    //... 
} 
+0

謝謝,尼斯解釋。但仍然不清楚只有「如」。我嘗試了'var button = somebutton as UIButton',它拋出了一個錯誤。 – Ranbijay

+0

你得到的錯誤是什麼? somebutton是UIButton類型的實例還是UIButton的子類?如果沒有,那麼將會拋出一個錯誤。如果某個類是該類的實例或子類的實例,則只能將其轉換爲某個類。 – user1419265