IT story

Swift에서 클래스가 프로토콜을 따르도록 만드는 방법은 무엇입니까?

hot-time 2020. 7. 14. 08:03
반응형

Swift에서 클래스가 프로토콜을 따르도록 만드는 방법은 무엇입니까?


Objective-C에서 :

@interface CustomDataSource : NSObject <UITableViewDataSource>

@end

스위프트에서 :

class CustomDataSource : UITableViewDataSource {

}

그러나 오류 메시지가 나타납니다.

  1. 'CellDatasDataSource'유형이 'NSObjectProtocol'프로토콜을 준수하지 않습니다.
  2. 'CellDatasDataSource'유형이 'UITableViewDataSource'프로토콜을 준수하지 않습니다.

올바른 방법은 무엇입니까?


'CellDatasDataSource'유형이 'NSObjectProtocol'프로토콜을 준수하지 않습니다.

NSObject에 맞게 클래스를 상속 해야합니다 NSObjectProtocol. 바닐라 스위프트 수업은 그렇지 않습니다. 그러나 많은 부분이 UIKit기대 NSObject합니다.

class CustomDataSource : NSObject, UITableViewDataSource {

}

하지만 이것은:

'CellDatasDataSource'유형이 'UITableViewDataSource'프로토콜을 준수하지 않습니다.

예상됩니다. 클래스가 프로토콜의 모든 필수 메소드를 구현할 때까지 오류가 발생합니다.

그래서 코딩하십시오 :)


프로토콜을 준수하기 전에 클래스는 상위 클래스에서 상속해야합니다. 주로 두 가지 방법이 있습니다.

한 가지 방법은 당신의 클래스 NSObjectUITableViewDataSource함께 상속 받도록 하는 것입니다. 이제 프로토콜에서 함수를 수정 override하려면 함수 호출 전에 다음과 같이 키워드를 추가해야 합니다.

class CustomDataSource : NSObject, UITableViewDataSource {

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

        // Configure the cell...

        return cell
    }
}

그러나 준수해야 할 프로토콜이 많고 각 프로토콜에 여러 델리게이트 기능이있을 수 있기 때문에 코드가 지저분해질 수 있습니다. 이 경우을 사용하여 프로토콜 준수 코드를 기본 클래스에서 분리 할 수 있으며 확장 extensionoverride키워드 를 추가 할 필요가 없습니다 . 따라서 위 코드와 동등한 것은

class CustomDataSource : NSObject{
    // Configure the object...
}

extension CustomDataSource: UITableViewDataSource {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

        // Configure the cell...

        return cell
    }
}

Xcode 9는 Swift Datasource & Delegates의 모든 필수 메소드를 구현하는 데 도움이됩니다.

예를 들면 다음과 같습니다 UITableViewDataSource.

필수 메소드를 구현하기위한 경고 / 힌트를 표시합니다.

enter image description here

Click on 'Fix' button, it will add all mandatory methods in code:

enter image description here

참고URL : https://stackoverflow.com/questions/24991018/how-to-make-a-class-conform-to-a-protocol-in-swift

반응형