使用 'where' 仅处理 swift 'if let' 中的其他条件

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

我有一个逻辑条件:

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

是否有任何选项可以以某种方式编写 if let condition to not handle true condition(因为我不想对此做任何事情)?所以,类似否定的东西:

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

感谢您的帮助。

您的 if 条件中的第一个分支实际上由 2 个条件组成:

  • if let 是对非空
  • 的检查
  • where 是后续条件的语法糖,当您可以确定变量不为空时。

你可以这样反转逻辑:

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

在 Swift 1.2 中,这样的事情是不可能的,但你可以使用:

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

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

这在逻辑上与您想要的实现相同。注意:因为 &&|| 运算符都将表达式的右侧包裹在闭包中,所以强制解包甚至是 "safe".

期待 Swift 2 我们得到一个新的 guard 语句,它首先处理 else 部分:

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

// use the unwrapped login here if you want