1

I have a list of ATM, each ATM has a name.

Now I want to check if my textField.text is equal to that name of each ATM. Surely, I can do this with for loop like so:

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

But the question here is I want another way to archive this.

Any helps would be appreciated, thanks.

UPDATE 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)
        }
    }

Work now, thanks for the answer.

2
  • There isn't another way to do it. If you have a names array, you could do: names.contains(nameTextField.text) Commented Apr 8, 2016 at 5:53
  • If I create a names array, I still need a for loop to assign atm's name to each element. Commented Apr 8, 2016 at 5:54

1 Answer 1

4

You can do this:

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
}

It will check the first atm that matches

Sign up to request clarification or add additional context in comments.

6 Comments

It doesn't present an alert when I type a same name, could you check my update.
Of course it doesn't. It just check if textfield content is equal to any atm's name. It was what you were asking for, wasn't it?
po atms.filter({$0.name == nameTextField.text}).first nil
Is your addButtonTapped(sender: UIButton) called? Have you linked the action correctly?
Yes, it is called, but I po atms.filter({$0.name == nameTextField.text}).first, it goes nil.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.