Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 interesting with 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.

like image 514
edzio27 Avatar asked Jul 05 '15 22:07

edzio27


2 Answers

In Swift 1.2 something like this is not possible but you can use:

// since where is logically the same as &&
if !(login != nil && validateLogin(login!)) {
    // This is interesting
}

// or
if login == nil || !validateLogin(login!) {
    // This is interesting
}

which is logically the same as your desired implementation. Note: because both the && and the || operator wrap the right side of the expression in a closure the force unwrap is even "safe".

Looking forward to Swift 2 we get a new guard statement which handles the else part first:

guard let login = login where validateLogin(login) else {
    // This is interesting
}

// use the unwrapped login here if you want
like image 107
Qbyte Avatar answered Oct 20 '22 01:10

Qbyte


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
}
like image 32
Code Different Avatar answered Oct 20 '22 00:10

Code Different