0
0
iOS Swiftmobile~3 mins

Why Identifiable protocol in iOS Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple protocol can save your app from confusing mix-ups and crashes!

The Scenario

Imagine you have a list of items in your app, like a grocery list. You want to update, delete, or reorder items. Without a way to uniquely identify each item, your app gets confused about which item to change.

The Problem

Manually tracking each item's position or comparing whole items every time is slow and error-prone. If two items look similar, your app might update the wrong one or crash. This makes your code complicated and buggy.

The Solution

The Identifiable protocol gives each item a unique ID automatically. This way, SwiftUI and your code know exactly which item is which. It makes updating lists smooth, safe, and simple.

Before vs After
Before
struct Item {
  var name: String
}

// No unique ID, hard to track items
After
struct Item: Identifiable {
  var id = UUID()
  var name: String
}

// Each item has a unique id automatically
What It Enables

It enables effortless, reliable updates and animations in dynamic lists by uniquely identifying each element.

Real Life Example

Think of a to-do app where tasks can be added, removed, or reordered. Using Identifiable ensures the app always knows which task you're editing or deleting, even if tasks have the same name.

Key Takeaways

Manually tracking items is confusing and error-prone.

Identifiable protocol assigns a unique ID to each item automatically.

This makes list updates and UI changes smooth and reliable.