Collection Helpers
Collection extensions for grouping, deduplication, safe access, and chunking.
extension Sequence {
/// Group elements by key
func grouped<Key: Hashable>(by keyPath: KeyPath<Element, Key>) -> [Key: [Element]] {
Dictionary(grouping: self) { $0[keyPath: keyPath] }
}
/// Return unique elements preserving order
func uniqued<Key: Hashable>(by keyPath: KeyPath<Element, Key>) -> [Element] {
var seen = Set<Key>()
return filter { element in
let key = element[keyPath: keyPath]
return seen.insert(key).inserted
}
}
}
extension Array {
/// Safe subscript that returns nil for out-of-bounds
subscript(safe index: Int) -> Element? {
indices.contains(index) ? self[index] : nil
}
/// Chunk array into smaller arrays
func chunked(into size: Int) -> [[Element]] {
stride(from: 0, to: count, by: size).map {
Array(self[$0..<Swift.min($0 + size, count)])
}
}
}
// Usage:
// let users = [User(id: 1, role: "admin"), User(id: 2, role: "user")]
// let byRole = users.grouped(by: \.role)
// let unique = users.uniqued(by: \.id)
// let chunks = [1,2,3,4,5].chunked(into: 2) // [[1,2], [3,4], [5]]