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

时间:2015-04-04 07:22:54

标签: ios swift tuples optional

我想知道是否有人有一种更优雅的方式来检查一下元组中的值是否为Nil?

目前我正在检查:

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

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

如果可能的话,我想要更简洁一些。

2 个答案:

答案 0 :(得分:6)

您可以使用元组值上的开关案例来完成此操作。例如:

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绑定。

答案 1 :(得分:0)

@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({ $0 as? (String, String) }))
print("cast:", c2.flatMap({ $0 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({ $0.object as? Credentials })
    .filterMap({ $0 as? (String, String) })
    .observeValues({ print("signal:", $0) })

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