在 Swift 中针对 Nil 值漂亮地测试多个变量

Tal*_*ion 0 if-statement ios swift

有没有什么漂亮的方法来测试下面的内容?我有多个parameters我需要知道其中是否有任何一个是nil

这就是我现在正在使用的,我确信有一种有效的方法可以测试所有并输入nil一次,但不确定如何:

if title == nil || name == nil  || height == nil || productName == nil {
            //Do something
        }
Run Code Online (Sandbox Code Playgroud)

我正在使用ObjectMapper并且在他们的时候,他们不支持错误处理,因此,我的init() throws错误和我需要检查来自的值Map是否为 nil 以及是否为 nil 。

San*_*eep 5

我在 CollectionType 上创建了一个简单的扩展来检查 Optional 值的集合,如果至少一个元素不为零,是否所有元素都有值或没有值。

extension CollectionType where Generator.Element == Optional<AnyObject>, Index.Distance == Int  {

    func allNotNil() -> Bool {
       return !allNil()
    }

    func atleastOneNotNil() -> Bool {
        return self.flatMap { $0 }.count > 0
    }

    func allNil() -> Bool {
        return self.flatMap { $0 }.count == 0
    }
}


var title: String? = ""
var name: String? = ""
var height: Float? = 1
var productName: String? = ""

[title, name, height, productName].allNotNil()
[title, name, height, productName].atleastOneNotNil()
[title, name, height, productName].allNil()
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你可以这样使用它,

 if [title, name, height, productName].atLeastOneNotNil() {

  }
Run Code Online (Sandbox Code Playgroud)

或者,您可以丢弃上面的扩展名,然后像这样简单地使用它,

 if [title, name, height, productName].flatMap { $0 }.count > 0 {

 }
Run Code Online (Sandbox Code Playgroud)

对于 Swift 4,

extension Collection where Element == Optional<Any> {

    func allNotNil() -> Bool {
        return !allNil()
    }

    func atleastOneNotNil() -> Bool {
        return self.flatMap { $0 }.count > 0
    }

    func allNil() -> Bool {
        return self.flatMap { $0 }.count == 0
    }
}
Run Code Online (Sandbox Code Playgroud)

Swift 5 的更新,

几乎没有添加新功能,CollectionType例如first(where:)allSatisfy(where:),这里使用它。

扩展集合 where Element == Optional {

func allNil() -> Bool {
    return allSatisfy { $0 == nil }
}

func anyNil() -> Bool {
    return first { $0 == nil } != nil
}

func allNotNil() -> Bool {
    return !allNil()
}
Run Code Online (Sandbox Code Playgroud)

}