ios – 使用Swift中的对象过滤2D数组

我创建了以下结构来显示tableview:

struct Section {    
    var heading : String
    var items : [MusicModel]   
    init(category: String, objects : [MusicModel]) {        
       heading = category
       items = objects
   }
}

然后我有以下函数将对象添加到数组:

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
}

因此,tableview可以很好地加载数据的节头和行.我希望能够过滤表格单元格,但是很难确定基于用户选择的仪器过滤对象数组的正确语法,并将其发送到过滤函数.这是我有的:

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

仅当snare或tenor为true时才返回该对象.我得到的错误是:
无法使用类型为'(@noescape(MusicModel)throws – > Bool)’的参数列表调用’filter’

任何的想法?如果您对更好的方法有建议我会非常感激.谢谢!

最佳答案 使用此更新的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
    }
}
点赞