edzio27
edzio27

Reputation: 4140

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.

Upvotes: 8

Views: 12428

Answers (2)

Qbyte
Qbyte

Reputation: 13243

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

Upvotes: 7

Code Different
Code Different

Reputation: 93181

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
}

Upvotes: 5

Related Questions