如何检查数组中的所有字段包含数据
问题描述:
我想检查数组以查看是否所有字段都有值,并且如果所有字段都有值,那么我希望它做某件事。我的代码确实有用,但它确实很麻烦。我想知道是否有更简单的方法来做到这一点。如何检查数组中的所有字段包含数据
@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")
}
}
答
做这个尝试的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")
}
答
您可以用filter
功能
if textData.filter({$0.isEmpty}).count > 0 {
// there is at least one empty item
} else {
// all items contain data
}
显示的TextData的日志。 – Shoaib