2015-09-04 84 views
0

我想檢查數組以查看是否所有字段都有值,並且如果所有字段都有值,那麼我希望它做某件事。我的代碼確實有用,但它確實很麻煩。我想知道是否有更簡單的方法來做到這一點。如何檢查數組中的所有字段包含數據

@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") 

    } 

} 
+0

顯示的TextData的日誌。 – Shoaib

回答

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") 
} 
2

您可以用filter功能

if textData.filter({$0.isEmpty}).count > 0 { 
    // there is at least one empty item 
} else { 
    // all items contain data 
} 
相關問題