Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Identifiable Protocol in Swift
Written by Team Kodeco

Identifiable is a protocol in Swift that requires conforming types to have a unique identifier property, which can be used to distinguish instances of the type.

For example, consider the following struct that represents a task in a task list app:

struct Task: Identifiable {
  let id = UUID()
  let name: String
  let isComplete: Bool
}

Here, the Task struct conforms to the Identifiable protocol by providing a unique id property using the UUID struct. This id can be used to distinguish instances of Task in a collection or array, allowing for easy updates and deletions of specific tasks.

Difference Between Hashable and Identifiable

Hashable and Identifiable are two different protocols in Swift that serve different purposes.

The Hashable protocol requires that an object be able to be hashed into a unique value, used as an identifier in collections. Hashable is often used to make custom classes usable as keys in dictionaries or as elements in sets.

The Identifiable protocol is used with collections of unique elements, requiring that each element have a unique identifier. Identifiable is often used with SwiftUI views to keep track of individual views and manage the rendering of dynamic views.

In summary, Hashable is used for hashing objects into unique values for collections, while Identifiable is used for identifying unique elements within collections.

© 2024 Kodeco Inc.