Search code examples
iosswiftuitextfield

Check if the integer value of a text field is valid in a switch statement [swift]


I've been attempting to check if the integer value of a text field is valid in a switch statement to cover more possible cases rather having long if/elseif statements.

switch characterTextFields {
case Int(characterTextFields[1].text!) == nil:
    validationErrorModal(text: "Level must be a number!")
}

The code above prompts the following error:

Expression pattern of type 'Bool' cannot match values of type '[UITextField]?'

characterTextFields is an array of text fields. I did research about possibly solutions which involved using let and where keywords, but wasn't able to implement correctly. Any suggestions?


Solution

  • You could use switch for that, but you have to switch over that number, not over the input field:

    switch Int(characterTextFields[1].text!) {
        case nil:
            validationErrorModal(text: "Level must be a number!")
        case 0?:  // switch over optional value
            break
    }
    

    Usually it is simpler to handle the optional first, e.g. :

    guard let level = Int(characterTextFields[1].text!) else {
        validationErrorModal(text: "Level must be a number!")
        return
    }
    

    and then switch over the non-optional value:

    switch level {
       case 0:
         break
       default:
         break       
    }