본문 바로가기

Project/MovieClip

❌ 컴파일 오류 발생...

// ❌ 컴파일 오류 발생
snapshot.appendItems(viewModel.reviews, toSection: .myReviews)
// Error: Cannot convert value of type '[ReviewItem]' to expected argument type '[ProfileItem]'

 

🔥 원인

  • viewModel.reviews는 [ReviewItem] 타입이지만, Diffable DataSource는 ProfileItem을 다룬다.
  • 따라서 ReviewItem을 ProfileItem.review(ReviewItem)으로 변환해야 한다.

 

1. ProfileItem.review(ReviewItem)으로 변환하는 이유

Diffable DataSource는 ProfileItem 타입만 다룰 수 있음

enum ProfileItem: Hashable {
    case profile(MovieClipUser)
    case review(ReviewItem) // ✅ 리뷰 데이터를 담기 위한 case
}
  • ProfileItem이 Diffable DataSource에서 다루는 데이터 타입이기 때문에, ReviewItem을 ProfileItem.review(ReviewItem)으로 변환해야 한다.

 

✅ 변환하는 코드

let reviews = viewModel.reviews.map { ProfileItem.review($0) }

 

  • viewModel.reviews는 [ReviewItem] 타입이다.
  • 이를 .map { ProfileItem.review($0) }을 통해 각 리뷰를 ProfileItem.review(ReviewItem)로 변환한다.

 

✅ 예제

// ✅ Firebase에서 가져온 ReviewItem 데이터 예제
viewModel.reviews = [
    ReviewItem(id: "1", photos: ["url1"], content: "첫 번째 리뷰", date: Date(), rating: 4.5),
    ReviewItem(id: "2", photos: ["url2"], content: "두 번째 리뷰", date: Date(), rating: 3.0)
]

// ✅ 변환 후 ProfileItem.review 타입
let reviews = viewModel.reviews.map { ProfileItem.review($0) }
print(reviews)
// 결과: [.review(ReviewItem(id: "1", photos: ["url1"], content: "첫 번째 리뷰", date: Date(), rating: 4.5)), .review(ReviewItem(id: "2", photos: ["url2"], content: "두 번째 리뷰", date: Date(), rating: 3.0))]

 

 

 

🔥 reloadData() 메서드 

private func reloadData() {
    var snapshot = NSDiffableDataSourceSnapshot<ProfileSection, ProfileItem>()
    
    // ✅ 프로필 섹션 추가
    snapshot.appendSections([.profile])
    let currentUser = viewModel.user
    snapshot.appendItems([.profile(currentUser)], toSection: .profile)
    
    // ✅ 리뷰 섹션 추가
    snapshot.appendSections([.myReviews])
    let reviews = viewModel.reviews.map { ProfileItem.review($0) } // ✅ 리뷰 데이터를 ProfileItem.review 타입으로 변환
    snapshot.appendItems(reviews, toSection: .myReviews)
    
    // ✅ dataSource가 nil이 아닐 때만 적용
    guard dataSource != nil else { return }
    dataSource.apply(snapshot, animatingDifferences: true)
}