Search code examples
iosswiftoption-type

Handle only else condition in swift 'if let' using 'where'


I have a logic condition:

if let login = login where validateLogin(login) {
    // I'm not interested in this condition
} else {
    // This is interesting
}

Is there any option to write somehow if let condition to not handle true condition (because I dont want to do anything with that)? So, something like negation:

!(if let login = login where validateLogin(login)) {
    // This is interesting
}

Thanks for help.


Solution

  • The first branch in your if condition is actual made up of 2 criteria:

    • if let is a check for non-null
    • where is a syntactic sugar for a follow up condition, when you can be sure that the variable is not null.

    You can reverse the logic like this:

    if login == nil || !validateLogin(login!) {
        // do something
    }