Chino Pan Chino Pan - 1 month ago 16
iOS Question

Convert if else structure into switch case in swift

I am pretty new in programming, I am trying to convert this if else structure into Switch cases in Swift language, i appreciate your help, thanks.

here is my code

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "ShowDefinition") {
if let destinationViewController = segue.destinationViewController as? EnglishViewController {
if let definition = sender as? String {
if definition == "Abstraction" {
destinationViewController.titleMsg = "Abstraction"
destinationViewController.definitionMsg = "definition 1"
} else if definition == "Binary System" {
destinationViewController.titleMsg = "Binary System"
destinationViewController.definitionMsg = "definition 2"
} else if definition == "Computer" {
destinationViewController.titleMsg = "Computer"
destinationViewController.definitionMsg = "definition 3"

} else if definition == "Internet" {
destinationViewController.titleMsg = "Internet"
destinationViewController.definitionMsg = "definition 4"

} else if definition == "Virtual Reality" {
destinationViewController.titleMsg = "Virtual Reality"
destinationViewController.definitionMsg = "definition 5"

}
}
}
}
}

Answer

Something like this:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "ShowDefinition") {
        if let destinationViewController = segue.destinationViewController as? EnglishViewController {
            if let definition = sender as? String {
                switch definition {
                case "Abstraction":
                    destinationViewController.titleMsg = "Abstraction"
                    destinationViewController.definitionMsg = "definition 1"
                case "Binary System":
                    destinationViewController.titleMsg = "Binary System"
                    destinationViewController.definitionMsg = "definition 2"
                case "Computer":
                    destinationViewController.titleMsg = "Computer"
                    destinationViewController.definitionMsg = "definition 3"
                case "Internet":
                    destinationViewController.titleMsg = "Internet"
                    destinationViewController.definitionMsg = "definition 4"
                    destinationViewController.titleMsg = "Abstraction"
                    destinationViewController.definitionMsg = "definition 1"
                case "Virtual Reality":
                    destinationViewController.titleMsg = "Virtual Reality"
                    destinationViewController.definitionMsg = "definition 5"
                default:
                    destinationViewController.titleMsg = ""
                    destinationViewController.definitionMsg = ""
                }
            }
        }
    }
}

Check what you want to do with the default value, that will be hit if none of the case matches.

Comments