Swift – Throwing functions

By | 02/03/2022

In this post, we will see how to use Throwing functions to handle errors in our code.

We start opening Xcode and we create a Playground file called Errors where, we will define a simple method “Divide” to divide two number greater than 1:

import UIKit

func Divide(_ val1: Double, _ val2: Double) -> Double {
    let result = val1/val2
    return result
}
 
var result = Divide(8,5)
print("The result is \(result)")


If we run the code, this will be the result:

The code runs well but, if we want to add some rules about values in input, we should change code in this way:

import UIKit

func Divide(_ val1: Double, _ val2: Double) -> Double {
    if(val1<=0 || val2<=0)
    {
        print("The input value must be greater than 0")
        return 0
    }
    if(val1>100 || val2>100)
    {
        print("The input value must be less than 100")
        return 0
    }
    if(val1 == val2)
    {
        print("The input values must be different")
        return 0
    }
    
    let result = val1/val2
    return result
}
 
var result = Divide(4,2)
print("The result is \(result)")



If we run the code, these will be the results:

We can see that it doesn’t work fine because, if the rules are not respected, the output value will be always 0 and it isn’t correct.
In order to fix this problem, we can use the Throwing functions that are simple functions but that can throw errors when there are problems.
We start defining an Enum, called ErrorsList, that represent the error conditions.
It adopts Error protocol and it indicates that a type can be used for error handling:

enum ErrorsList: Error {
    case valuesMustGreaterThan0
    case valuesMustLessThan100
    case valuesMustBeDifferent
}



Then, we modify the method Divide in order to transform it in a Throwing function:

// If we mark a Function with 'throws', it means that it is a throwing function
// and can throw an error,
func Divide(_ val1: Double, _ val2: Double) throws -> Double {
    if(val1<=0 || val2<=0)
    {
        throw ErrorsList.valuesMustGreaterThan0
    }
    if(val1>100 || val2>100)
    {
        throw ErrorsList.valuesMustLessThan100
    }
    if(val1 == val2)
    {
        throw ErrorsList.valuesMustBeDifferent
    }
    
    return val1/val2
}



Finally, we modify the code in order to use the new method Divide:

do{
    let result = try Divide(4,4)
    print("The result is \(result)")
}
catch ErrorsList.valuesMustBeDifferent{
    print("The input values must be different")
}
catch ErrorsList.valuesMustGreaterThan0{
    print("The input value must be greater than 0")
}
catch ErrorsList.valuesMustLessThan100{
    print("The input value must be less than 100")
}
// this is for unexpected errors
catch {
    print("Unexpected error: \(error).")
}



If we run the code, these will be the results:



Leave a Reply

Your email address will not be published.