search by tags

for the user

adventures into the land of the command line

swift dictionary grouping

I recently discovered this awesome feature in Swift

Say you have a list of things, let's say a list of dictionaries.

myObj = [
            [
                "date": "2019-03-01",
                "message": "Hey there!"
            ],
            [
                "date": "2019-03-02",
                "message": "Hi again!"
            ],
            [
                "date": "2019-03-01",
                "message": "Bye!"
            ]
        ]

And you want to group these things by some recurring value.

var grouped = Dictionary(grouping: myObj, by: { $0["date"]! })

print(grouped)

    [
        "2019-03-01": [
            [
                "date": "2019-03-01",
                "message": "Hey there!"
            ],
            [
                "date": "2019-03-01",
                "message": "Bye!"
            ]
        ],
        "2019-03-02": [
            [
                "date": "2019-03-02",
                "message": "Hi again!"
            ]
        ]
    ]

Awesome.