Clean way to filter an array of dictionaries by unique dictionary values

前端 未结 2 1559
情深已故
情深已故 2021-01-14 06:04

Say I have an object:

struct Foo {
    let id: Int
    let bar: Int
}

Now I have 5 of these objects in an array:

let foo1 =         


        
2条回答
  •  我在风中等你
    2021-01-14 06:39

    I'm not a fan of the accepted answer. Having the set outside the closure that uses it doesn't seem appropriate. I would rather keep everything contained. There's a CS term that applies but I don't remember what it is...

    I would rather see this:

    let uniquedBars = fooArray
        .reduce(into: (result: [Foo](), set: Set())) { partial, next in
            if partial.set.insert(next.bar).inserted {
                partial.result.append(next)
            }
        }
        .result
    

提交回复
热议问题