1

In my Xcode7 Swift2 project, I have a Class called Recipe that is of type NSObject and NSCoding and has a variable called name that is a String:

class Recipe: NSObject, NSCoding {

    var name: String

    ...
}

This array of names is displayed in a TableViewController.

In a separate ViewController the user can add items to this array using a UITextField and UIButton. I don't want there to be two of the same names in the array. In the @IBAction of the UIButton, how can I search the array for the typed name, checking for duplicates? In the ViewController mentioned above, I reference the array as:

let recipes = [Recipe]()

I've looked here and tried:

@IBAction func saveReport(sender: UIButton) {

    let checkName = reportName.text!

    if recipes.contains("\(checkName)") {

        print("Found: \(checkName)")

    }

    ...
}

But it give an error:

enter image description here

How can I search the array for the typed name, using Swift2? Thank you!

Community
  • 1
  • 1
ChallengerGuy
  • 2,385
  • 6
  • 27
  • 43

2 Answers2

2

You can use contains but you have to give it a predicate instead of just the string you're searching:

if recipes.contains( { $0.name == checkName } ) {
    print("Found: \(checkName)")
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
1

The array recipes contains Recipe instances rather than strings.

An easy solution is to use the filter function to filter for a recipe with the string value in checkName

if !recipes.filter({$0.name == checkName}).isEmpty {
  print("Found: \(checkName)")
}
vadian
  • 274,689
  • 30
  • 353
  • 361