We want to know error handling mechanism in SWIFT for whole block of code.
As, in swift, there are some techniques used for error handling, some of them are like using guard or if let. Also we can achieve it using do - catch statement. But we are getting stuck while handling error for whole bunch of code using single try-catch block as we were doing in Objective-C. In Objective-C this block was easily handling errors within any line of code in it. So we want to know this type of mechanism in swift.
For now, we came to know that if we need to handle error, then use guard, if-let statement for each line, or write some custom methods which will throw the error and use that method in do-catch block. So is there any mechanism in Swift which will be parallel to try-catch block just like in Objective-C so we don’t need to write if-let or guard statement for each single line of code in that whole bunch of code.
This is how we used if-let and guard let for single line statement null handling :
if-let implementation sample code snippet :-
if let title = dict["title"].string
{
let myTitle = title
}
But below is mentioned scenario in which we want solution in swift for try-catch block within delegate functions.
A sample code snippet in Objective-C using try-catch block
- (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);
}
}
Above is the code snippet which we were using in Objective-C. But now we want to use same thing of try-catch in Swift. But till now we haven’t found any solution. So how do we handle such scenario in which we can add the try-catch block to delegate functions of table view, collection view, ... , etc.