Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Collection Protocol in Swift
Written by Team Kodeco

In Swift, arrays, sets and dictionaries all conform to the Collection protocol. This means that they share a common set of methods and properties that can be used on any collection.

By using the Collection protocol, you can write more flexible and reusable code that can work with any kind of collection, rather than having to write separate code for each type of collection.

Here’s an example of how you can use the Collection protocol to write a function that prints the first element of any collection:

func printFirstElement<C: Collection>(_ collection: C) {
  guard let first = collection.first else {
    print("The collection is empty.")
    return
  }
  print(first)
}

In this example, the <C: Collection> syntax is called a type constraint, it specifies that the generic type C must conform to the Collection protocol.

You can call this function with any collection, such as an array, set, or dictionary. For example:

let numbers = [1, 2, 3]
printFirstElement(numbers) // Prints "1

let words = Set(["apple", "banana", "cherry"])
printFirstElement(words) // Prints "cherry" 

Remember sets are unordered, so your output may vary.

© 2024 Kodeco Inc.