Table of contents
Hi All, As I told in the previous articles that I have started a #100DaysOfSwiftUI challenge this is my learning from Day 8. where I have learned about Passing default values for parameters in function and errors in Swift. Let's go through it at once:
Default Values For Parameters
So what happens some times in 8 out 10 times we just want same value for a parameter and just provide the flexibility we create a parameter in function but don't want to call the function with that same value every time use that function we can make use of the Default value for the parameter offered by swift.
Default parameter values make function calls easier by letting us provide command defaults for parameters. So when we want to call that function using the default value we can just ignore the parameter and swift will use the default value we are providing and when we want some custom value we can call the parameter with our required value. Here is an example:
func findDirections(from: String, to: String, route: String = "fastest", avoidHighways = false) {
}
So as we can see in this code that I am assigning the fastest value to the route parameter and value false to avoidHighways. As we know when we want to find a route to someplace we always want to be the fastest way and want to cover the distance through the highway to reach the destination faster and safer. But let's just say we are going on a road trip then we don't want to reach the destination faster we want to reach the destination while enjoying the scenic view on the way and in some cases, we even want to avoid the highways so we can enjoy country side view. then the use the function like this:
findDirection(from: "London", to:"Glosgow")
findDirection(from: "London", to:"Glosgow", route: "scenic")
findDirectionfrom: "London", to:"Glosgow", route: "scenic", avoidHighway = true)
In the above example first, we are using both route and avoidHighway default values by ignoring the parameters. In the second function call, we want the route to be scenic not the fastest by default so we provide custom value for the variable route and we are still not avoiding highway by using default value and in the last function call we custom value for both route and avoidHighway so we can have fun on the road trip.
Error In Functions
Things can wrong everywhere not just in our code but we always should be equipped so that when we do have those errors we handle them properly so that our program doesn't crash and burn. so Swift makes us handle errors - or at least acknowledge when they might happen.
Error handling takes three steps:
- Telling swift about the possible error that can happen.
- Writing Function that can flag up errors if they happen.
- Calling that function, and handling any error that might happen.
let's see how one can work through the error by solving a problem: If the user asks us to check how strong their password is, we'll flag up a series error if the password is too short or is obvious.
So first we need to define the possible error that can happen. So for that, we'll define an enum listing all the possible error scenarios.
enum PasswordError: Error {
case short, obvious
}
So there are 2 types of possible errors the password is too short or he using a common password used everywhere. Also, we are telling only that those types of errors are there and not what those errors mean.
Step two is to write a function that will trigger one of those errors. when an error is triggered - or thrown in Swift - we're saying something fatal went wrong with the function, and instead of continuing as normal it immediately terminates without sending back any value.
func checkPassword(_ password: String) throws -> String {
if password.count < 5 {
throw PasswordError.short
}
if password == "12345" {
throw PasswordError.obvious
}
if password.count < 8 {
return "OK"
} else if password.count < 10 {
return "Good"
} else {
return "Excellent"
}
}
let's break that down:
- if a function wants to throw errors without handling them itself, you must mark the function as throws before the return type
- we don't specify exactly what kind of error is thrown by the function, just that it can throw errors.
- Being marked with throws does not mean the function must throw errors, only that it might.
- when it comes a time to throw an error, we write throw followed by one or our PasswordError case. This immediately exits the function, meaning that it won't return the string.
- if no errors are thrown the function must behave like normal - it needs to return a string.
That completes the second step of throwing errors: we defined the errors that might happen, then wrote a function using those errors.
Now the final step of using that function and handling all the errors it can throw:
- Starting a block of work that might throw errors, using do.
- Calling one or more throwing functions, using try.
- Handling any thrown errors using catch.
let string = "12345"
do {
let result = try checkPassword(string)
print("Password rating: \(result)")
} catch PasswordError.short {
print("Please use a longer password.")
} catch PasswordError.obvious {
print("I have the same combination on my luggage!")
} catch {
print("There was an error.")
}
if the checkPassword() function works correctly, it will return a value into the result, which is then printed out. But if any errors are thrown (which in this case it will) the password rating message will not be printed out - execution will immediately jump to the catch block.
We can always have a specific catch block that will catch a specific case of an error such as catch Password.short or we will have genric catch which will catch all remaining types of error which is the last catch block in our code.
As you progress you’ll see how throwing functions are baked into many of Apple’s own frameworks, so even though you might not create them yourself much you will at least need to know how to use them safely.
Conclusion
So I have learned on the Day 8 of 100 Days of SwiftUI that how to use Default values for parameters, how to create and handle the errors in function and use cases of both.
Also, let me know if any mistakes are done in this blog/write-up I have done for Day 8 learning so I can fix my mistakes and improve my understandings.
Thank you.