|
Thank you for taking your time to help, all :) The challange is to " Refactor all the else statements we just added so that they call a new method called showErrorMessage(). This should accept an error message and a title, and do all the UIAlertController work from there."
This is how far i've got, and it just feels wrong...
Here are the code copied over from lecture:
|
|
A way you could handle the above logic and to make it look a little cleaner is by using a guard statement -
Just one way of doing it. Looks cleaner and very readable. The submit function will go to first guard statement. If true then it will flow to next guard statement and so on. If all guards are true then the word is fine. However if one of the guards is false it will go into the else statement of that guard and call the wordError function and present your alert. Just a couple of tips. Just make sure with your functions that if you return something then you have to have a return type in your function declaration. Your top submit function doesn't declare a return type but it returns a function call. You can achieve this but will probably be subject of another lesson. I can see your logic in wanting to use a switch statement for your errors but for this to work in these circumstances you would need to make each error an atual type by creating an enum. You would then use this enum to assign the error type based on what condition was not met, pass that error type into your showError function and then do the switch on that error type. On larger projects you may want to do this but i think Paul just wants to get you to think about other ways to handle multiple if/else statements and how else you can deal with them using Swift at a basic level. For this purpose i think using the guards above would be suitable. Hope this helps Dave |
|
@Newy11527 Thank you SO MUCH !! Wow , that was such a great explanation, Thanks again, and maybe i will try both methods (switch case and guard ) just to practice. |
|
Another solution is this:
Each time "showErrorMessage" is called and the "OK" button is pressed we return, no errors in the debug consule, you guys can use this version as well. I think is no need to declare those constants again. And this is the code block for this method: func showErrorMessage(errorTitle: String, errorMessage: String) {
|
TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and more!
This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.