简体   繁体   中英

Filtering a 2D array with objects in Swift

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM