I have an array of Item
. The order is never guaranteed as the collection is served from an API based on a number of user actions elsewhere.
However I need to order this collection by a type
field so I can iterate over it elsewhere correctly.
In the case of the example playground below, I need a reordered collection that would follow this logic:
[
Item(type: .foo),
Item(type: .bar),
Item(type: .boo),
Item(type: .baz),
Item(type: .boom),
Item(type: .bang)
]
Specifically .foo
and .bar
should be the first 2 items, .boom
and bang
will be the last 2 items.
These fixed items are unique, no duplicates will exist in the response.
Everything left over should be between these 2 groups, in the same order as they are in the original collection.
I have tried to split the item into 2 collections within var output: [Item]
and insert the second collection at an index, however the ordering is still off.
How can I achieve this?
import UIKit
enum ItemType: String {
case foo
case bar
case boo
case baz
case boom
case bang
}
struct Item {
let type: ItemType
}
let props = [
Item(type: .bang),
Item(type: .bar),
Item(type: .baz),
Item(type: .boo),
Item(type: .boom),
Item(type: .foo)
]
/*
case foo
case bar
> ----------- should be ordered in same order as in `props`
case boom
case bang
*/
var output: [Item] {
var fixedPosition: [Item] = []
var dynamicPosition: [Item] = []
props.forEach { item in
if (item.type == .foo || item.type == .bar || item.type == .boom || item.type == .bang ){
fixedPosition.append(item)
} else {
dynamicPosition.append(item)
}
}
var result: [Item] = fixedPosition
result.insert(contentsOf: dynamicPosition, at: 1)
return result
}
print(output.map { $0.type })