Hashable하게 Compositional Layout Section 생성하기

donotinto·2024년 3월 30일

Compositional Layout의 Section을 enum으로 관리하면서 다음 문제가 있었습니다.

import UIKit

enum ExampleCompositionalLayout: Int, CaseIterable {
    
    case typeFirst
    case typeSecond
    
    static func create() -> UICollectionViewCompositionalLayout {
        
        let layout = UICollectionViewCompositionalLayout { section, environment in
            
            let section = ExampleCompositionalLayout(rawValue: section)
            
            switch section {
            case .typeFirst:
            	return createTypeFirst()
            case .typeSecond:
                return createTypeSecond()
            case nil:
                return nil
            }

        }
        
        return layout
    }
    
    private static func createTypeFisrt() -> NSCollectionLayoutSection { ... }
    
    private static func createTypeSecond() -> NSCollectionLayoutSection { ... }
}

보시다시피 section의 index을 통해 enum과 함께 쓰면 섹션 별로 원하는 레이아웃을 잡을 수 있고 직관적이여서 합이 좋지만,
enum을 있는 그대로 사용하니 한계가 있었습니다.

위처럼 날짜별로 Section이 추가되어야 하기 때문에, 추가되는 날짜에 맞추어 enum case를 무한히 증가시켜야 했습니다.

snapshot.appendItems(["test"], toSection: .typeFirst)

이를 현실적으로 날짜별로 모두 케이스를 만들 수가 없기 때문에 enum의 특성을 이용해봐야겠다 생각했습니다.

바로 enum의 연관값을 사용하여 Hashable한 case로 Section을 계속하여 만든는 것입니다.

switch type {
	case .typeFirst:
		return createTypeFirst()
	case .typeSecond(let date):
		return createTypeSecond()
	case .none:
		return nil
}

물론 같은 모양의 섹션이면 하나의 케이스로 모두 대응할 수 있지만, 그렇게 된다면 Hashable한 Diffable DataSource를 사용하지 못합니다.

enum을 확장하여 사용할 때 연관값을 이용하면 이런식으로 응용이 가능하다는 점을 배울 수 있었습니다.

0개의 댓글