reza23
reza23

Reputation: 3385

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. 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. Can this be done? Any suggestions.

Upvotes: 0

Views: 57

Answers (1)

vacawama
vacawama

Reputation: 154603

It doesn't work because a UIView doesn't conform to the protocol. You need to create a custom UIView subclass that does:

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.

Upvotes: 3

Related Questions