seq.grouped(by:)
๐ replit
// โญ๏ธ seq.grouped(by:)
extension Sequence {
public func grouped<Key>(
by keyForValue: (Element) -> Key
) -> [Key: [Element]]
{
return Dictionary(grouping: self, by: keyForValue)
}
}
๐ paiza.io
// `Dictionary` conforms to `Sequence`
let dict = [ // Dictionary<Key, Value>
"Sam": 79, "Joe": 5, "Mary": 18, // Key = String
"Tom": 5, "Alex": 82, "Nancy": 1 // Value = Int
] // Element = (key: Key, value: Value) โญ๏ธ
// โญ๏ธ seq.grouped(by:)
let grouped = dict.grouped { $0.value } // โญ๏ธ grouped by element's `value`
// โญ๏ธ ไนๅฏๅฏซๆ๏ผ dict.grouped(by: \.value) // โญ๏ธ keypath as functions
/*
[
18: [(key: "Mary" , value: 18)],
5 : [(key: "Tom" , value: 5), (key: "Joe", value: 5)],
82: [(key: "Alex" , value: 82)],
1 : [(key: "Nancy", value: 1)],
79: [(key: "Sam" , value: 79)]
]
*/
// โญ๏ธ Dictionary(grouping:by:)
let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
let studentsByFirstLetter = Dictionary(
grouping: students,
by: { $0.first! }
)
/// [
/// "E": ["Efua"],
/// "K": ["Kofi", "Kweku"],
/// "A": ["Abena", "Akosua"]
/// ]
SwiftUI Tutorials โฉ Composing Complex Interfaces โฉ
Sec. 2: Create a Category List - Step 2.
Swift ranking dictionary - build ranking list from scores
Last updated