Reputation: 43
I have create the following struct to display a tableview:
struct Section {
var heading : String
var items : [MusicModel]
init(category: String, objects : [MusicModel]) {
heading = category
items = objects
}
}
Then I have the following function to add objects to the array:
var sectionsArray = [Section]()
func getSectionsFromData() -> [Section] {
let basicStrokes = Section(category: "Basic Strokes",
objects: [MusicModel(title: Title.EightOnAHand, author: .None, snare: true, tenor: true)])
sectionsArray.append(basicStrokes)
return sectionsArray
}
So the tableview loads just fine with section header and rows for the data. I want to be able to filter the table cells but am having a tough time figuring out the proper syntax to filter an array of objects based on a user selected instrument that is sent to a filtering function. Here is what I have:
func getMusic(instrument: MusicData.Instrument) -> [Section] {
if instrument == .Tenor {
let filtered = sections.filter {$0.items.filter {$0.tenor == true}}
return filtered
} else {
let filtered = sections.filter {$0.items.filter {$0.snare == true}}
return filtered
}
}
The object is returned only if snare or tenor is true. The error that I am getting is: Cannot invoke 'filter' with an argument list of type '(@noescape (MusicModel) throws -> Bool)'
Any idea? If you have a suggestion on better way to do this I would greatly appreciate it. Thanks!
Upvotes: 4
Views: 1865
Reputation: 1236
Or the following one. (Be warned that your Section is struct
, which means it'll be copied around.)
func getMusic(instrument: MusicData.Instrument) -> [Section] {
return sections.map { (var s: Section) -> Section in
s.items = s.items.filter { instrument == .Tenor ? $0.tenor : $0.snare }
return s
}
}
Upvotes: 0
Reputation: 4825
Use this updated getMusic method,
func getMusic(instrument: MusicData.Instrument) -> [Section] {
if instrument == .Tenor {
var filtered = sections.filter {$0.items.filter {$0.tenor == true}.count > 0}
filtered = filtered.map({ (var section: Section) -> Section in
section.items = section.items.filter {$0.tenor == true}
return section
})
return filtered
} else {
let filtered = sections.filter {$0.items.filter {$0.snare == true}.count > 0}
filtered = filtered.map({ (var section: Section) -> Section in
section.items = section.items.filter {$0.snare == true}
return section
})
return filtered
}
}
Upvotes: 2