Filtering a 2D array with objects in Swift

I create the following structure 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
}

Thus, the tableview loads just fine with the section heading and rows for the data. I want to be able to filter table cells, but I find it difficult to find the correct syntax for filtering an array of objects based on a user-selected tool that is sent to the filter 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
    }
}

An object is returned only if the trap or tenor is correct. The error I get: Cannot call 'filter' using argument list like '(@noescape (MusicModel) throws -> Bool)'

Any idea? If you have a suggestion on a better way to do this, I would really appreciate it. Thank!

+4
2

getMusic,

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
    }
}
+2

. ( , struct, , .)

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
        }
    }
0

All Articles