【问题标题】:How do I make a class conform to a protocol in swift?如何让一个类快速符合协议?
【发布时间】:2014-06-03 20:35:24
【问题描述】:

为了实现委托,我需要使类符合 Swift 中的协议。我该怎么做?

【问题讨论】:

    标签: ios swift


    【解决方案1】:
    class YourClass: SuperClassIfAny, FirstProtocol, SecondProtocol {
    }
    

    但请注意,某些协议要求您实现委托方法。例如,UITableViewDataSource要求您实施

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

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

    如果那些不是由符合协议的类实现的,Xcode 会给你一个编译错误(总是检查协议声明,Cmd + Click 会告诉你你必须实现哪些方法)。

    【讨论】:

    • 希望它显示一个比“不符合协议”更有用的错误
    • 同意,我实际上花了一些时间试图找出它没有编译的原因。不过,我认为这是一件好事,可以防止您犯愚蠢的错误。如果他们添加了一个更具描述性的错误,那就太酷了:-P
    【解决方案2】:

    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;这并不能远程回答问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多