Grouping

In Swift 4 they added the ability for grouping. This post contains an example of using it on an Array.

In Swift 4 they added the ability for grouping and more.

In this example we are going to group an Array of Friends by location.


// 1. Create a struct
struct Friend {
    let name: String
    let location: String

    init(name: String, location: String) {
        self.name = name;
        self.location = location;
    }
}

// 2. An array that contains our struct of Friend
var data:[Friend] = []


// 3. Append some Friends to the array
data.append(Friend.init(name: "Tony", location: "Italy"))
data.append(Friend.init(name: "Frank", location: "Italy"))
data.append(Friend.init(name: "Rocco", location: "Italy"))
data.append(Friend.init(name: "Kelly", location: "Canada"))
data.append(Friend.init(name: "Jose", location: "Spain"))
data.append(Friend.init(name: "Jose", location: "Maria"))

// 4. Now create a grouped dictionary
let groupedDictionary = Dictionary(grouping: data) { (b) -> String in
    return b.location
}

// 5. Print out the results
print(groupedDictionary)

// 6. Print out the results for friends from Italy
print("-----")
print(groupedDictionary["Italy"])