我正在编写一个试图使用自定义协议定义函数的工厂类。编译器抛出错误,因为我不知道如何将协议定义添加到函数参数。
示例:
protocol MyCustomFunctions {
func customFunction()
}
class MyVC: UIViewController, MyCustomFunctions {
func customFunction() {}
}
class Factory {
func createButton(specificVC: UIViewController) // need protocol here
{
specificVC.customFunction() // error thrown
}
}
如何在变量定义期间使用特定的协议?
还是有另一种方式吗?
答案 0 :(得分:1)
首先,惯例表示课程以大写字母开头。
class MyVC: UIViewController, MyCustomFunctions {
func customFunction() {}
}
然后你需要的是参数
中的正确类型class factory: NSObject {
func createButton(specificVC: MyVC) // you need a class that conforms to protocol here.
{
specificVC.customFunction() // no error anymore
}
}
你有另一种选择。你可以简单地在论证中承诺你不会透露对象的完整类型,你只会说它是一个符合协议的不透明对象。
class factory: NSObject {
func createButton(specificVC: MyCustomFunctions) // you need a class that conforms to protocol here.
{
specificVC.customFunction() // no error anymore
}
}
<强>奖金:强>
您可以对此进行推理并找到答案的方式是&gt;
当我调用specificVC.customFunction()
时抛出错误...嗯...所以这个对象只能运行这个函数,如果它是实际具有该函数的类型。那么让我们来看看参数类型--UIViewController - ..UIViewController肯定没有这个功能。这是MyVC或协议。
Swift中的类型安全性非常严格。只需“按照类型流程”,你就会很好。