2016-04-08 73 views
1

我有一个ATM列表,每个ATM都有一个名称。如何检查textField是否等于数组中的字符串

现在我想检查我的textField.text是否等于每个ATM的名称。当然,我可以这样做for循环像这样:

for atm in atms { 
    if nameTextField.text == atm.name { 
     // Do some Stuff 
    } 
} 

但这里的问题是我想要另一种方式来存档此。

任何帮助将不胜感激,谢谢。

更新1:现在

@IBAction func addButtonTapped(sender: UIButton) { 
     if let _ = atms.filter({$0.name == nameTextField.text}).first { 
      let alert = UIAlertController(title: "This name has been added!", message: nil, preferredStyle: .Alert) 
      alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) 
      presentViewController(alert, animated: true, completion: nil) 
     } else if nameTextField.text != "" && addressTextField.text != "" && latitudeTextField.text != "" && longitudeTextField.text != "" { 
      saveData() 
      dismissViewControllerAnimated(true, completion: nil) 
     } else { 
      let alert = UIAlertController(title: "Missing Info", message: nil, preferredStyle: .Alert) 
      alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) 
      presentViewController(alert, animated: true, completion: nil) 
     } 
    } 

工作,感谢您的回答。

+0

没有另一种方式来做到这一点的第一个大气压。如果你有一个names数组,你可以这样做:'names.contains(nameTextField.text)' –

+0

如果我创建一个names数组,我仍然需要一个for循环来为每个元素指定atm的名字。 – Khuong

回答

4

你可以这样做:

if let atm = atms.filter({$0.name == nameTextField.text}).first { 
    //Show alert 
    let alert = UIAlertController(title: "This name has been added!", message: nil, preferredStyle: .Alert) 
    let action = UIAlertAction(title: "Ok", style: .Default, handler: nil) 
    alert.addAction(action) 
    presentViewController(alert, animated: true, completion: nil) 
} else { 
    //do another stuff 
} 

它会检查符合

+0

当我输入相同的名称时,它不会显示警报,您是否可以检查我的更新? – Khuong

+0

当然不是。它只是检查文本内容是否等于任何atm的名字。这是你要求的,不是吗? –

+0

那么如何以你的方式显示警戒? – Khuong

相关问题