GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: Project 5- challenge 2

Forums > 100 Days of Swift

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."

  • i tried to do a switch / case for the error messages, but then now I am stuck and not sure how to move forward. Am i even on the right track?? Should i even be using switch case?

This is how far i've got, and it just feels wrong...

    func submit(_ answer: String) {
        let lowerAnswer = answer.lowercased()

        if isPossible(word: lowerAnswer){
            if isReal(word: lowerAnswer){
                if isOriginal(word: lowerAnswer) {
                    if isReal(word: lowerAnswer) {

                        usedWords.insert(answer, at: 0)
                        score += 1

                        let indexpath = IndexPath(row:0, section: 0)
                        tableView.insertRows(at: [indexpath], with: .automatic)
                        return
                }
            }
        }
    }
    return showErrorMessage()
}

    func showErrorMessage(){
        let errorTitle: String
        let errorMessage: String

        switch conditions {
            case
        }

    }

Here are the code copied over from lecture:

func submit(answer: String) {
    let lowerAnswer = answer.lowercased()

    let errorTitle: String
    let errorMessage: String

    if isPossible(word: lowerAnswer) {
        if isOriginal(word: lowerAnswer) {
            if isReal(word: lowerAnswer) {
                usedWords.insert(answer, at: 0)

                let indexPath = IndexPath(row: 0, section: 0)
                tableView.insertRows(at: [indexPath], with: .automatic)

                return
            } else {
                errorTitle = "Word not recognised"
                errorMessage = "You can't just make them up, you know!"
            }
        } else {
            errorTitle = "Word used already"
            errorMessage = "Be more original!"
        }
    } else {
        guard let title = title?.lowercased() else { return }
        errorTitle = "Word not possible"
        errorMessage = "You can't spell that word from \(title)"
    }

    let ac = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .alert)
    ac.addAction(UIAlertAction(title: "OK", style: .default))
    present(ac, animated: true)
}

3      

A way you could handle the above logic and to make it look a little cleaner is by using a guard statement -

func submit(_ answer: String) {
        let answer = newWord.lowercased()

        guard ifPossible(word: answer) else {
            showErrorMessage(title: "Word not possible", message: "You cant just make stuff up")
            return
        }

        guard isOriginal(word: answer) else {
            showErrorMessage(title: "Word used already", message: "Be more original")
            return
        }

        guard isReal(word: answer) else {
            showErrorMessage(title: "Word not recognised", message: "That isn't a real word")
            return
        }
 }

 func showErrorMessage(title: String, message: String) {
        errorTitle = title
        errorMessage = message

        let ac = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
  }

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

5      

@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.

4      

Another solution is this:

func submit(_ answer: String) {
    let lowerAnswer = answer.lowercased()

    if isPossible(word: lowerAnswer) {
        if isOriginal(word: lowerAnswer) {
            if isReal(word: lowerAnswer) {
                userWords.insert(answer, at: 0)

                let indexPath = IndexPath(row: 0, section: 0)
                tableView.insertRows(at: [indexPath], with: .automatic)

                return
            }

            showErrorMessage(errorTitle: "Word not recognised", errorMessage: "You can't just make them up, you know!")
            return
        }

        showErrorMessage(errorTitle: "This word is already used!", errorMessage: "New word is required!")
        return
    }

    guard let title = title?.lowercased() else { return }
    showErrorMessage(errorTitle: "Word not possible", errorMessage: "You can't spell that word from \(title)")
    return

}

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) {

    let alert = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default))
    present(alert, animated: true)
}

3      

Hacking with Swift+

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!

Learn more here

Archived topic

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.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.