How To Change A Statement Based On String?


(fey one) #1

Hi,
I am now dealing with a string of instructions that been feed by a text field.

the problem is, why this code doesn’t work? ‘instruction’ prints the string value I want to use correctly corresponding to the statement, but I always get the “wasn’t a recognized character” default case…

func processInputCommand() {
        print("processing called")
        let string = self.robotInstructions.text!
        let commands = Array(string.characters)
        let instruction = String(describing: commands.last)
        print(instruction)

            switch instruction {
            case "N" :
                self.usersRobot.yPosition = self.usersRobot.yPosition + 1
            case "S" :
                self.usersRobot.yPosition = self.usersRobot.yPosition - 1
            case "E" :
                self.usersRobot.xPosition = self.usersRobot.xPosition + 1
            case "W" :
                self.usersRobot.xPosition = self.usersRobot.xPosition - 1
            case "P" :
                pickUpGummyBears()
            case "D" :
                if self.usersRobot.numberOfBagsHeld > 0 {
                    dropGummyBears()
                } else {
                    print("THE ROBOT ISNT HOLDING ANY BAGS CURRENTLY")
                }
            default:
                print("WASNT RECOGNISED CHARACTER")
            }
    }

(yane sine) #2

In JDK 7 release, you may use a String object in the expression of a switch statement. Here is how I did it:

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
             break;
         case "Friday":
             typeOfDay = "End of work week";
             break;
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             break;
         default:
             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     }
     return typeOfDay;
}