👉🏻 이전 포스트에서 randomuser api 데이터를 struct구조로 변환해서 앱에서 데이터를 표현하도록 구현해봤습니다.
In the previous post, I converted the randomuser API data into a struct structure and implemented it to represent the data in the app.
이 struct구조에서 많이 사용되는 프로토콜이 Identifiable,Equatable,Hashable입니다.
The protocols that are widely used in this struct structure are Identifiable, Equatable, and Hashable.
https://www.freelifemakers.org/wordpress/index.php/2025/12/25/swift-infinitescreoo-refresh-loading/
👉🏻 아래는 이 프로토콜들의 기능을 이해하기 위한 대표인 기능만 구현했습니다.
Below, only representative functions are implemented to help you understand the functionality of these protocols.
👉🏻Identifiable , Hashable
Swift에서 위의 예제처럼 api데이터를 struct구조로 변환하여 앱에서 사용하는 구조등에서 Identifiable,Equatable,Hashable이 많이 사용됩니다.
In Swift, Identifiable, Equatable, and Hashable are widely used in structures used in apps by converting API data into struct structures, as in the example above.
struct나 클래스를 사용 할경우 인스턴스(객체)를 생성하게 됩니다.
When using a struct or class, an instance (object) is created.
이 때 아래처럼 동일한 값을 대입하여 인스턴스를 생성하면 반복문에서 출력시 반복문 내에서 각 인스턴스를 구분짓기가 힘들어집니다.
At this time, if you create an instance by substituting the same value as below, it becomes difficult to distinguish each instance within the loop when outputting it.
그래서 Identifiable이나,Hashable 프로토콜을 사용해서 각 인스턴스를 구분지을 수 있게 해줍니다.
So, we can use the Identifiable or Hashable protocol to distinguish each instance.
Identifiable은 사용자가 직접 id를 생성해서 구분 짓는 방법이고 Hashable 프로토콜을 사용하면 자동적으로 내부에 hash값이 생성되어 인스턴스를 구분지을 수 있게 해줍니다.
Identifiable is a method in which the user creates an id to distinguish them, and if the Hashable protocol is used, a hash value is automatically generated internally to distinguish instances.
인스턴스를 구분지어야하는 이유는 나중에 데이터의 추가 삭제 변경이 발생할때 필요하기 때문입니다.
The reason we need to distinguish between instances is because we need to do additional deletions and changes to the data later.
✔️ Identifiable은 이렇게 사용됩니다.
Identifiable is used like this:
Identifiable이 만족되면 SwiftUI의 List, ForEach 등에서 바로 사용 가능합니다.
Once Identifiable is satisfied, it can be used directly in SwiftUI’s List, ForEach, etc.
struct Person: Identifiable {
let id = UUID() // 고유 UUID 자동 생성
let name: String
let age: Int
}
List,ForEach에서 사용방법
How to use List, ForEach
import SwiftUI
struct Person: Identifiable {
// 고유 UUID 자동 생성 / Automatically generate unique UUID
let id = UUID()
let name: String
let age: Int
}
struct PersonListView: View {
let people: [Person] = [
Person(name: "Alice", age: 30),
Person(name: "Bob", age: 35),
Person(name: "Charlie", age: 25),
Person(name: "Diana", age: 28)
]
var body: some View {
List(people) { person in
HStack {
Text(person.name)
.font(.headline)
Spacer()
Text("\(person.age) years old")
.foregroundColor(.secondary)
}
}
.navigationTitle("People List")
}
}
✔️ Hashable은 이렇게 사용됩니다.
This is how Hashable is used:
Dictionary의 키로 사용할 수 있게 해줍니다.
Allows you to use it as a key in a dictionary.
struct Product: Hashable {
let productID: Int
let name: String
}
Hashable이 적용된 struct는 다음과 같이 사용될 수 있습니다.
A struct with Hashable applied can be used as follows:
// prices딕셔너리를 Product와 Double타입으로 생성
// Create a prices dictionary with Product and Double types
var prices: [Product: Double] = [:]
// 값이 같은 인스턴스1 / Instance 1 with the same value
let iPhone = Product(productID: 1, name: "iPhone 15")
let iPad = Product(productID: 2, name: "iPad Pro")
// 1500000와 같은값, 언더스코어는 무시됨.
// Same value as 1500000, underscores are ignored.
prices[iPhone] = 1_500_000
prices[iPad] = 1_200_000
// 같은 제품으로 가격 조회 / Check price for the same product
// 값이 같은 인스턴스2 / Instance 2 with the same value
let sameiPhone = Product(productID: 1, name: "iPhone 15")
print(prices[sameiPhone] ?? 0) // 1500000.0
// 가격 업데이트 / price update
prices[sameiPhone] = 1_450_000
print(prices[iPhone]!) // 1450000.0
👉🏻 Equatable
✔️ 생성된 인스턴스(객체)의 내용(값)을 비교하기 위해서 사용되는 프로토콜입니다.
This is a protocol used to compare the contents (values) of created instances (objects).
✔️ Equatable은 다음과 같이 사용합니다.
Equatable is used like this:
struct Person: Equatable {
let name: String
let age: Int
let email: String
}
let p1 = Person(name: "김철수", age: 30, email: "kim@example.com")
let p2 = Person(name: "김철수", age: 30, email: "kim@example.com")
print(p1 == p2) // true ← Swift가 자동으로 모든 프로퍼티 비교해줌
✔️ Swift 초기 버전(예: Swift 3~4.0) 스타일로, Equatable을 직접 구현한 형태입니다.
This is a direct implementation of Equatable in the style of early Swift versions (e.g. Swift 3-4.0).
✔️ 원래는 static func == 이렇게 == 이름인 함수를 만들어 주고 == 이 연산자가 호출되면
static func == 이 함수가 호출되는 형태입니다.
Originally, a function named == was created like this: static func == , and when the == operator was called,
static func == This function was called.
✔️ 하지만 swift4.1부터는 Equtable프로토콜을 사용하고 == 연산자만 호출하면 swift가 자동으로 함수를 만들어 줍니다.
However, starting from Swift 4.1, if you use the Equtable protocol and only call the == operator, Swift will automatically create a function.
struct Person: Equatable {
let name: String
let age: Int
let email: String
static func == (lhs: Person, rhs: Person) -> Bool {
return lhs.name == rhs.name && lhs.age == rhs.age
// email은 비교에 포함 안 됨
}
}
👉🏻 결론은 identifiable과 Hashable은 동일한 값을 가진 인스턴스를 반복문이나 콜렉션에서 구분짓기 위해서 사용되는 거고 Equatable은 인스턴스의 값을 쉽게 비교할 수있게 해주는 프로토콜 입니다.
In conclusion, identifiable and Hashable are used to distinguish instances with the same value in loops or collections, and Equatable is a protocol that allows for easy comparison of instance values.