我們希望知道SWIFT中的錯誤處理機制以完成整個代碼塊。Swift 2.0異常處理
因爲,在迅速,有一些技術用於錯誤處理,其中一些像使用guard
或if let
。我們也可以使用do - catch
聲明來實現它。但是我們在處理整個代碼時使用單個try-catch塊處理錯誤時卡住了,正如我們在Objective-C
中所做的那樣。在Objective-C
這個塊很容易處理任何代碼行內的錯誤。所以我們想要快速瞭解這種機制。
現在,我們才知道,如果我們需要處理錯誤,然後用guard
,if-let
聲明每一行,或寫這將引發錯誤,並使用該方法在do-catch
塊的一些自定義的方法。那麼Swift中有沒有什麼機制可以像Objective-C
那樣平行於try-catch
塊,所以我們不需要爲整個代碼中的每一行代碼編寫if-let
或guard
語句。
這是我們如何使用if-let
和guard
讓單行聲明空處理:
if-let
實施示例代碼段: -
if let title = dict["title"].string
{
let myTitle = title
}
但低於提到的場景中,我們希望迅速解決代理函數中的try-catch
塊。
try-catch
使用塊
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
@try {
static NSString *itemIdentifier = @"CustomCell";
//Some line of code where exception may occur…
//Some line of code where exception may occur…
//Some line of code where exception may occur…
//Some line of code where exception may occur…
//…
//…
//…
return cell;
}
@catch (NSException *exception) {
NSLog(@"Exception in cellForItemAtIndexPath - %@「,exception.description);
}
}
上面Objective-C
甲示例代碼段是我們使用在Objective-C
的代碼片段。但是現在我們想在Swift中使用try-catch
。但直到現在我們還沒有找到任何解決方案。那麼,我們如何處理這種情況,我們可以將try-catch
塊添加到委託表視圖,集合視圖等功能中。
看到這個:http://iosdevcenters.blogspot.in/2015/12/error-handling-in-swift-20.html –
@KiritModi - 請再讀一遍我的問題...我想單一的嘗試趕上塊爲線束..我不想把每條線的if-let或gaurd ... – Nayan
我的情況是完全一樣的像「hpux735」。請查看他對「jawbroken」的回覆 - https://forums.developer.apple.com/message/10227#10227 – Nayan