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

时间:2016-02-25 00:15:42

标签: ios arrays swift filter

我创建了以下结构来显示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
    }
}

仅当圈套或次要为真时才返回对象。我得到的错误是: 无法调用'过滤'使用类型'的参数列表(@ noescape(MusicModel)throws - > Bool)'

有什么想法吗?如果您对更好的方法有建议我会非常感激。谢谢!

2 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:0)

或者以下一个。 (警告你的部分是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
        }
    }