检查元组中任一值是否为零的优雅方法

Elegant way to check if either value in a Tuple is nil

我想知道是否有人有更优雅的方法来检查 Tuple 中的 either 值在 Swift 中是否为 Nil?

目前我正在这样检查:

    var credentials = CredentialHelper.getCredentials() //returns a tuple of two Optional Strings.

    if (credentials.username == nil || credentials.password == nil)
    {
        //continue doing work.
    }

如果可能的话,我想要更简洁的内容。

您可以在元组值上使用 switch case 来完成。例如:

func testTuple(input: (String?, String?)) -> String {
    switch input {
    case (_, .None), (.None, _):
        return "One or the other is nil"
    case (.Some(let a), _):
        return "a is \(a)"
    case (_, .Some(let b)):
        return "b is \(b)"
    }
}

testTuple((nil, "B"))  // "One or the other is nil"
testTuple(("A", nil))  // "One or the other is nil"
testTuple(("A", "B"))  // "a is A"
testTuple((nil, nil))  // "One or the other is nil"

诀窍是对元组值使用 let 绑定。​​

@Abizern 在需要 if case let 的全部功能的情况下将其钉牢。有些情况下你不需要,例如,使用映射选项或使用 ReactiveCocoa,在这种情况下,好的旧转换会有所帮助,特别是当你需要所有值并且元组不是特别长时:

import ReactiveCocoa
import ReactiveSwift

typealias Credentials = (u: String?, p: String?)
var notification = Notification.Name("didReceiveCredentials")

var c1: Credentials? = ("foo", "bar")
var c2: Credentials? = ("foo", nil)

print("cast:", c1.flatMap({ [=10=] as? (String, String) }))
print("cast:", c2.flatMap({ [=10=] as? (String, String) }))

if let (u, p) = c1 as? (String, String) { print("if:", u, p) }
if let (u, p) = c2 as? (String, String) { print("if:", u, p) }

NotificationCenter.default.reactive.notifications(forName: notification)
    .filterMap({ [=10=].object as? Credentials })
    .filterMap({ [=10=] as? (String, String) })
    .observeValues({ print("signal:", [=10=]) })

NotificationCenter.default.post(name: notification, object: c1)
NotificationCenter.default.post(name: notification, object: c2)