Reputation: 2395
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:
How can I search the array
for the typed name
, using Swift2
? Thank you!
Upvotes: 1
Views: 244
Reputation: 70094
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)")
}
Upvotes: 2
Reputation: 285039
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)")
}
Upvotes: 1