如何使一个类符合Swift中的协议? [英] How to make a class conform to a protocol in Swift?

查看:99
本文介绍了如何使一个类符合Swift中的协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中:

in Objective-C:

@interface CustomDataSource : NSObject <UITableViewDataSource>

@end

在Swift中:

class CustomDataSource : UITableViewDataSource {

}

但是,将出现错误消息:

However, an error message will appear:

  1. 类型'CellDatasDataSource'不符合协议'NSObjectProtocol'
  2. 类型'CellDatasDataSource'不符合协议'UITableViewDataSource'

正确的方法应该是什么?

What should be the correct way ?

推荐答案

类型'CellDatasDataSource'不符合协议'NSObjectProtocol'

Type 'CellDatasDataSource' does not conform to protocol 'NSObjectProtocol'

您必须使您的类继承自NSObject以符合NSObjectProtocol. Vanilla Swift类没有.但是UIKit的许多部分都期望NSObject s.

You have to make your class inherit from NSObject to conform to the NSObjectProtocol. Vanilla Swift classes do not. But many parts of UIKit expect NSObjects.

class CustomDataSource : NSObject, UITableViewDataSource {

}

但是这个:

类型'CellDatasDataSource'不符合协议'UITableViewDataSource'

Type 'CellDatasDataSource' does not conform to protocol 'UITableViewDataSource'

是预期的.您将得到错误,直到您的类实现协议的所有必需方法为止.

Is expected. You will get the error until your class implements all required methods of the protocol.

因此获取编码:)

这篇关于如何使一个类符合Swift中的协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆