본문 바로가기

Project/MovieClip

❌ 문제 해결... ProfileItem이 Hashable 및 Equatable 프로토콜을 준수하지 않는다?

❓ ProfileItem 열거형에 기존의 MovieClipUser 라는 구조체를 데이터 타입으로 사용할 경우 에러 발생 

 

📍데이터 모델 (Item) 만들기

enum ProfileItem: Hashable {
    case profile(MovieClipUser)  // 기존 모델 사용
    ...
}

 

📍기존 데이터 모델 

struct MovieClipUser: Codable {
    let id: String
    var username: String = ""
    var createOn: Date = Date()
    var bio: String = ""
    var avatarPath: String = ""
    var clipMovies: [String] = []
    var isUserOnboarded: Bool = false
    
    init(from user: User) {
        self.id = user.uid
    }
    
}

⚠️ 에러 원인 분석

에러 메시지는 ProfileItem이 Hashable 및 Equatable 프로토콜을 준수하지 않는다는 뜻

Profile/ProfileDataModel.swift:19:6 Type 'ProfileItem' does not conform to protocol 'Equatable'
Profile/ProfileDataModel.swift:19:6 Type 'ProfileItem' does not conform to protocol 'Hashable'

 

💡 왜 발생했을까?

  • Swift에서 enum이 Hashable이 되려면, 모든 연관 값을 가진 케이스의 타입도 Hashable이어야 함
  • 하지만 MovieClipUser는 현재 Hashable을 따르지 않음. (Codable만 따르고 있음)

 

✅ 해결 방법

MovieClipUser를 Hashable로 확장하면 해결 가능!

extension MovieClipUser: Hashable {
    static func == (lhs: MovieClipUser, rhs: MovieClipUser) -> Bool {
        return lhs.id == rhs.id
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}

📌 이 코드의 의미

  • == 연산자를 정의하여 같은 유저인지 비교 가능하도록 함 (id가 같으면 같은 유저로 판단)
  • hash(into:)를 정의하여 Hashable 프로토콜을 만족하도록 설정
  • 이렇게 하면 DiffableDataSource에서 MovieClipUser를 사용할 수 있음! 🚀

https://explorer89.tistory.com/344

 

✅ hash(into:) 메서드와 == 연산자의 역할

📍 구조체 내 hash, == 메서드struct TvResultItem: Hashable { let tvResult: TvTMDBResult let sectionType: TvSectionType func hash(into hasher: inout Hasher) { // tvResult.id와 sectionType을 조합해서 고유 해시 생성 hasher.combine(tvResult

explorer89.tistory.com