Imagine you have an array of _Device_ objects and you want to group them by category as shown in the image below:

Grouping Array Elements With Dictionary in Swift

Grouping Device object by category

How should you go about in solving this problem?

Before Swift 5, the most straightforward way is to loop through each device in the array and manually assign each element to its respective category. In Swift 5, Apple has introduced a generic dictionary initializer to help developers deal with this kind of situation with just 1 single line of code.

Wondering how this can be done? Read on to find out more.


Introducing init(grouping:by:)

In Swift 5, Apple introduced a “grouping by” dictionary initializer. According to the documentation, the initializer has a definition of:

Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key.

To better understand the definition, let’s revisit the example that we saw at the beginning of this article.

Let’s say you have a Device struct and an array of Device objects as shown below:

struct Device {
	    let category: String
	    let name: String
	}

	let deviceArray = [
	    Device(category: "Laptop", name: "Macbook Air"),
	    Device(category: "Laptop", name: "Macbook Pro"),
	    Device(category: "Laptop", name: "Galaxy Book"),
	    Device(category: "Laptop", name: "Chromebook"),
	    Device(category: "Mobile Phone", name: "iPhone SE"),
	    Device(category: "Mobile Phone", name: "iPhone 11"),
	    Device(category: "Mobile Phone", name: "Galaxy S"),
	    Device(category: "Mobile Phone", name: "Galaxy Note"),
	    Device(category: "Mobile Phone", name: "Pixel")
	]

#software-developer #ios-development #swift-5 #swift

Grouping Array Elements With Dictionary in Swift
6.90 GEEK