074_MVVM+DiffableDataSource(Unsplash: Get a random photo)

2022. 10. 22. 22:21SeSAC/과제

#. 체크리스트

 1. Codable사용할 때 옵셔널 타입 체크하기: Observable.value를 nil로 초기화 하려면 옵셔널 타입이어야 함.

 2. snapshot.appendItems()에 클로저값 넣을 때 viewDidLoad보다 Codable이 먼저 실행(서치바검색어가 전달되지 않은 상황)됨. 결국 스냅샷에 nil을 넣는 상황이 되기 때문에 nil이 아닌 경우에 bind메서드 실행하도록 분기 처리 해줘야함.

 

1.

struct RandomPhoto: Codable, Hashable {
    var description: String?
    var urls: randomPhotoUrls?
}

// MARK: - randomPhotoUrls
struct randomPhotoUrls: Codable, Hashable {
    let raw, full, regular, small, thumb: String
}

//코더블 RandomPhoto타입을 초기화
var randomPhoto: CObservable<RandomPhoto> = CObservable(RandomPhoto(description: "", urls: nil))

 

2.

 func bindData() {
        viewModel.randomPhoto.bind { photo in
            var snapshot = NSDiffableDataSourceSnapshot<Int, randomPhotoUrls>()
            snapshot.appendSections([0])
            guard let data = photo.urls else { return }
            snapshot.appendItems([data])
            print(photo.urls)
            self.dataSource.apply(snapshot)
        }