Wondering if someone could help me out with filtering using predicates in Swift.
I have a somewhat messy datasource that I am using to populate a UITableView. The d
If you do not insist on NSPredicate
(don't see a reason why you should since you're not using NSFetchRequest
, ...), here's the code:
struct Exercises {
let category: String
let name : String
let x_seed: [Double]
let y_seed: [Double]
let hasMult: Bool
}
let exercises = [
Exercises(category:"Sports", name:"Bowling", x_seed:[125,155,185], y_seed:[3.00, 3.73, 4.43], hasMult:false),
Exercises(category:"Sports", name:"Water Polo", x_seed:[125,155,185], y_seed:[10.00, 12.40,14.80], hasMult:false),
Exercises(category:"Sports", name:"Handball", x_seed:[125,155,185], y_seed:[12.00, 14.87, 17.77], hasMult:false),
Exercises(category:"Sports", name:"Dancing", x_seed:[125,155,185], y_seed:[3.00, 3.73, 4.43], hasMult:true),
Exercises(category:"Sports", name:"Frisbee", x_seed:[125,155,185], y_seed:[3.00, 3.73, 4.43], hasMult:false),
Exercises(category:"Sports", name:"Volleyball", x_seed:[125,155,185], y_seed:[3.00, 3.73, 4.43], hasMult:false),
Exercises(category:"Sports", name:"Archery", x_seed:[125,155,185], y_seed:[3.50, 4.33, 5.17], hasMult:false),
Exercises(category:"Sports", name:"Golf", x_seed:[125,155,185], y_seed:[3.50, 4.33, 5.17], hasMult:true)
]
let options = NSStringCompareOptions.CaseInsensitiveSearch | NSStringCompareOptions.DiacriticInsensitiveSearch
// Filter exercises by name (case and diacritic insensitive)
let filteredExercises = exercises.filter {
$0.name.rangeOfString("Ol", options: options) != nil
}
let filteredExerciseNames = ", ".join(filteredExercises.map({ $0.name }))
println(filteredExerciseNames)
It prints Water Polo, Volleyball, Golf.