“协议需要功能与类型”是什么意思?

问题描述:

我正在使用委托来传递我存储在函数中的值。每当我尝试实现委托到我的另一个类,我得到错误“AnswerViewController”不符合协议“TagToIndex委托”。扩展,错误产生:“协议需要功能与类型”是什么意思?

协议需要函数'finishPassing(dictionary :)'与类型'(Dictionary) - >()'你想添加一个存根吗?

这是协议:

protocol TagToIndexDelegate { 
func finishPassing (dictionary:Dictionary<Int,Int>) 
} 

这里是我想从发送变量的函数:

extension MyCell: YSSegmentedControlDelegate { 

func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt index: Int) { 
    tagToIndex[actionButton.tag] = index 

    delegate?.finishPassing(dictionary: tagToIndex) 
} 

func segmentedControl(_ segmentedControl: YSSegmentedControl, didPressItemAt index: Int) { 

}} 

哪里delegateTagToIndexDelegate型的,和变量tagToIndex这存在于willPressItemAt之内是我传递的数据。

最后,类我想实现TagToIndexDelegate

class AnswerViewController: UIViewController, TagToIndexDelegate { 
override func viewDidLoad() { 
    super.viewDidLoad() 

} 
} 

我觉得我已经做了某种根本性的错误,但我没有足够的熟悉斯威夫特知道是什么错误。

谢谢, 尼克

您已定义协议TagToIndexDelegate这需要实现的方法finishPassing (dictionary:Dictionary<Int,Int>)。然后,你说你的AnswerViewController类符合TagToIndexDelegate,但你永远不会实际实现所需的方法。该类需要实施所需的方法以满足一致性。

的错误暗示这将是您可以添加一个存根:

optional func finishPassing (dictionary:Dictionary<Int,Int>)

func finishPassing (dictionary:Dictionary<Int,Int>) 
{ 
    // logic here 
} 

您还可以通过在它前面加上optional这样的更改协议函数声明可选

至于什么是正确的做法,您必须根据应用程序中实际发生的情况来决定。