大器晩成

[프로토콜] - 서브스크립트 본문

iOS/Swift 문법

[프로토콜] - 서브스크립트

zerobugpark 2025. 2. 6. 00:36

[서브스크립트 요구사항]

  • get, set 키워드를 통해 읽기/쓰기 여부를 설정 (최소한의 요구사항)
  • get 키워드 -> 최소한 읽기 서브스크립트로 구현 / 읽기, 쓰기 모두 구현 가능합니다.
  • get/set 키워드 -> 반드시 읽기, 쓰기 모두 구현해야 합니다.
protocol Numbers {
    subscript(idx: Int) -> Int { get }
}

struct Number: Numbers {
    
//    subscript(idx: Int) -> Int {
//        get {
//            return 0
//        }
//    }
    
    subscript(idx: Int) -> Int {
        get {
            return 0
        } set {
            
        }
    }
    
    
    
}

 

 

프로토콜은 일반적으로 확장에서 채택을 합니다.

class ViewController: UIViewController {

}


extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        

    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        

    }
    
    
}
  • colletcionView protocol 채택
  • 참고: 확장에서 작성한 메서드는 재정의가 불가능합니다.
728x90