0
0
iOS Swiftmobile~5 mins

Identifiable protocol in iOS Swift

Choose your learning style9 modes available
Introduction

The Identifiable protocol helps us give each item a unique ID. This makes it easy to find, update, or show items in lists.

When showing a list of items in a SwiftUI view and each item needs a unique ID.
When you want to update or delete a specific item in a collection easily.
When working with data models that need to be uniquely identified.
When using ForEach in SwiftUI to display dynamic lists.
When syncing data between views and models where each item must be distinct.
Syntax
iOS Swift
struct MyItem: Identifiable {
  var id = UUID()
  var name: String
}

The id property must be unique for each instance.

You can use any type for id as long as it conforms to Hashable, but UUID is common.

Examples
Here, id is an integer that uniquely identifies each user.
iOS Swift
struct User: Identifiable {
  var id: Int
  var username: String
}
This example uses UUID() to automatically create a unique ID.
iOS Swift
struct Product: Identifiable {
  var id = UUID()
  var title: String
}
You can also use a String as the unique ID.
iOS Swift
struct Task: Identifiable {
  let id: String
  let description: String
}
Sample App

This SwiftUI view shows a list of fruits. Each fruit is an Item with a unique id. SwiftUI uses the id to track each row.

iOS Swift
import SwiftUI

struct Item: Identifiable {
  var id = UUID()
  var name: String
}

struct ContentView: View {
  let items = [
    Item(name: "Apple"),
    Item(name: "Banana"),
    Item(name: "Cherry")
  ]

  var body: some View {
    List(items) { item in
      Text(item.name)
    }
  }
}
OutputSuccess
Important Notes

Always make sure id is unique to avoid bugs in lists.

If your data already has a unique property, you can use it as id instead of creating a new one.

Identifiable helps SwiftUI know which views changed, so it updates only those views.

Summary

The Identifiable protocol requires a unique id for each item.

It is very useful for lists and dynamic views in SwiftUI.

Use simple types like UUID, Int, or String for the id.