James
James

Reputation: 45

switch statement only executes default case Swift

So I am just beginning to learn Swift and for this assignment, what I want it to do is as you type the language from a list shown on the screen, it will return "hello world" in that same language. I have a switch statement in and for some reason it is only executing the default case. I think I have it set up correctly, it should be like all switch statements?

This is what I have so far in my code.

 class ViewController: UIViewController {

    @IBOutlet weak var myLabel: UILabel!

    @IBOutlet weak var myField: UITextField!

    @IBOutlet weak var myImage: UIImageView!

    @IBAction func buttonPressed(_ sender: Any) {
        myLabel.text = myField.text
        let language: String = "English"
        switch language {
            case "French":
            myLabel.text = "Bonjour le monde"
            case "Spanish":
            myLabel.text = "Hola mundo"
            case "German":
            myLabel.text = "Hallo welt"
            case "Italian":
            myLabel.text = "Ciao mondo"
            default:
            myLabel.text = "Hello world"
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        myField.text = myLabel.text
    }
}

I've tried it with breaks after each case, but it still outputs the default case. Am I doing this correctly? Remember I'm very very new to Swift

Upvotes: 0

Views: 473

Answers (1)

rvx
rvx

Reputation: 201

Every time you are giving language = "English". Thats why its executing Default case.

  @IBAction func buttonPressed(_ sender: Any) {
    let language: String = myField.text
   // use textfield text to check in Switch

    switch language {
        case "French":
        myLabel.text = "Bonjour le monde"
        case "Spanish":
        myLabel.text = "Hola mundo"
        case "German":
        myLabel.text = "Hallo welt"
        case "Italian":
        myLabel.text = "Ciao mondo"
        default:
        myLabel.text = "Hello world"
    }
}

Upvotes: 1

Related Questions