빈 셀을 빠르게 추가하기 위한 UICollectionView 확장

May 03 2023
Swift 코드 샘플 코드 위의 예에서 셀이 잘못된 클래스인 경우 디버깅 시 어설션 실패로 인해 앱이 중지됩니다. 그러나 프로덕션에서는 셀이 잘못된 클래스에 속하는 경우 빈 셀이 반환되고 앱이 계속 실행됩니다.

스위프트 코드 샘플

암호

final class FallbackBlankCollectionViewCell: UICollectionViewCell {}

extension UICollectionView {
    func blankCell(forIndexPath: IndexPath) -> UICollectionViewCell {
        register(FallbackBlankCollectionViewCell.self, forCellWithReuseIdentifier: "FallbackBlankCollectionViewCell")
        return dequeueReusableCell(withReuseIdentifier: "FallbackBlankCollectionViewCell", for: forIndexPath)
    }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LobbyCell", for: indexPath) as? LobbyCell {
            return cell
        } else {
            assertionFailure()
            return collectionView.blankCell(forIndexPath: indexPath)
        }
    }

위의 예에서 셀이 잘못된 클래스인 경우 디버깅 시 어설션 실패로 인해 앱이 중지됩니다. 그러나 프로덕션에서는 셀이 잘못된 클래스에 속하는 경우 빈 셀이 반환되고 앱이 계속 실행됩니다.