如何检查数组中的所有字段是否包含数据

时间:2015-09-04 18:26:49

标签: ios swift loops

我想检查数组以查看是否所有字段都有值,如果所有字段都有值,那么我希望它能做些什么。我的代码确实有效,但它确实非常混乱。我想知道是否有更简单的方法可以做到这一点。

@IBAction func testBtn(sender: AnyObject) {
          self.textData = arrayCellsTextFields.valueForKey("text") as! [String]

    for item in textData {
        if item.isEmpty {


        print("Missing")
            switchKey = true
          // alertviewer will go here
        break


        } else {

        switchKey = false
        }
    }

    if switchKey == false {
        //navigation here
        print("done")

    }

}

2 个答案:

答案 0 :(得分:2)

您可以使用filter功能

执行此操作
if textData.filter({$0.isEmpty}).count > 0 {
  // there is at least one empty item
} else {
  // all items contain data
}

答案 1 :(得分:1)

尝试guard.filter

的这种组合
@IBAction func testBtn(sender: AnyObject) {
    self.textData = arrayCellsTextFields.valueForKey("text") as! [String]
    guard textData.count == (textData.filter { !$0.isEmpty }).count else {
        print("Missing")
        return
    }
    print("Done")
}