[英]Swift 4+ instantiating a class variable that conforms to a protocol
I like to create a class, in my case a UIView, that conforms to a protocol, I then want to send that variable to a function. 我想创建一个符合协议的类(以UIView为例),然后将其发送给函数。 I have the following code:
我有以下代码:
protocol MyProtocol{
var aValue:Int{ get set }
}
func doSomething( myView:UIView & MyProtocol){
print( "a Value:\(myView.aValue )")
}
let rect = CGRect(x: 0, y: 0, width: 100, height: 100 )
var testView:UIView & MyProtocol = UIView(frame: rect ) as! UIView & MyProtocol
testView.aValue = 5
doSomething(myView: testView)
This code compiles but when I run it I get an error as testView can not be created. 这段代码可以编译,但是当我运行它时,由于无法创建testView而出现错误。 Can this be done?
能做到吗? Any suggestions.
有什么建议么。
It doesn't work because a UIView
doesn't conform to the protocol. 它不起作用,因为
UIView
不符合协议。 You need to create a custom UIView
subclass that does: 您需要创建一个自定义
UIView
子类,该子类可以执行以下操作:
class CustomView : UIView, MyProtocol {
var aValue = 0
}
var testView: UIView & MyProtocol = CustomView(frame: rect )
testView.aValue = 5
doSomething(testView: testView)
Output: 输出:
a Value:5
The protocol describes the interface that the instance will provide, but it doesn't allocate the storage for the new properties. 该协议描述了实例将提供的接口,但没有为新属性分配存储。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.