Search code examples
swiftmacosif-statementcase-sensitive

Swift Console input not case sensitive


i just started learning Swift3. For the beginning i write a console program for converting units. I have a console input stream

let typ = readLine()

and of cause i get the exact same string back but i use this in a if statement. Now my Problem i don't want to check it case sensitive i only want the plain string. This is the if construct i use:

if typ == unitA {
    print("foo")
    //Some Code
}else if typ == unitB{
    print("super foo")
    //Some Code
}else{
    print("Invalid input :/")
}

Thank you :D


Solution

  • Simply lowercase the input before comparing it. Also, a switch statement can greatly clean up the if/if else/else ladder.

    guard let input = readLine() else {
        fatalError("No input recieved")
    }
    
    switch input.lowercased() {
        case unitA: print("foo")
        case unitB: print("super foo")
        default: print("Invalid input :/")
    }