如何在Swift中使一个类符合某个协议?

20
我需要使一个Swift类符合协议以实现委托。我该如何做?
2个回答

43
class YourClass: SuperClassIfAny, FirstProtocol, SecondProtocol {
}

注意,一些协议要求你实现委托方法。例如,UITableViewDataSource要求你实现。
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int

并且。
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!

如果实现协议的类没有实现这些方法,Xcode 将会给你一个编译错误(记得检查协议声明,使用 Cmd + 点击可以查看你必须实现哪些方法)。

1
希望它能显示一个比“不符合协议”更有用的错误。 - Adam Waite
同意,我实际上花了一些时间试图找出为什么它没有编译。不过我认为这是一件好事,可以防止你犯愚蠢的错误。如果他们添加了更详细的错误描述,那就太棒了 :-P - Oscar Swanros

1

Xcode 6 beta 7略微更改了UITableViewDataSource协议的语法,以匹配以下两个必需实现的语法:

6b7: UITableViewDataSource

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell!

相对于6b6
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell

关键的不同之处在于,UITableView、NSIndexPath和UITableViewCell不再是“Implicitly Unwrapped Optionals”。

-1;这根本没有回答问题。 - Mark Amery

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接