[objective-c] 클래스가 Swift의 프로토콜을 준수하도록 만드는 방법은 무엇입니까?
Objective-C에서 :
@interface CustomDataSource : NSObject <UITableViewDataSource>
@end
Swift에서 :
class CustomDataSource : UITableViewDataSource {
}
그러나 오류 메시지가 나타납니다.
- ‘CellDatasDataSource’유형이 ‘NSObjectProtocol’프로토콜을 준수하지 않습니다.
- ‘CellDatasDataSource’유형이 ‘UITableViewDataSource’프로토콜을 준수하지 않습니다.
올바른 방법은 무엇입니까?
답변
‘CellDatasDataSource’유형이 ‘NSObjectProtocol’프로토콜을 준수하지 않습니다.
.NET Framework NSObject를 준수하려면 클래스를 상속 해야합니다 NSObjectProtocol. 바닐라 스위프트 클래스는 그렇지 않습니다. 그러나 많은 부분이 UIKit기대 NSObject합니다.
class CustomDataSource : NSObject, UITableViewDataSource {
}
하지만 이것은:
‘CellDatasDataSource’유형이 ‘UITableViewDataSource’프로토콜을 준수하지 않습니다.
예상됩니다. 클래스가 프로토콜의 모든 필수 메서드를 구현할 때까지 오류가 발생합니다.
그래서 코딩을 얻으십시오 🙂
답변
클래스는 프로토콜을 따르기 전에 부모 클래스에서 상속해야합니다. 주로 두 가지 방법이 있습니다.
한 가지 방법은 클래스 NSObject가 UITableViewDataSource함께 상속 하고 준수하도록하는 것입니다. 이제 프로토콜의 함수를 수정하려면 다음 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
}
}
그러나 준수해야 할 프로토콜이 많고 각 프로토콜에 여러 위임 기능이있을 수 있으므로 코드가 복잡해집니다. 이 경우를 사용하여 프로토콜 준수 코드를 기본 클래스에서 분리 할 수 있으며 확장 extension에 override키워드 를 추가 할 필요가 없습니다 . 따라서 위의 코드에 해당하는 것은
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
}
}


