I'm trying to create a protocol that would be implemented by certain classes, all of them should also implement UIScrollViewDelegate
. What I thought of is for my new protocol to implement the protocol UIScrollViewDelegate
.
protocol MyProtocol: UIScrollViewDelegate {
var myVar: NSString { get }
func myMethod()
}
As the protocol should have its default implementation I also created an extension for this protocol.
extension MyProtocol {
func myMethod() {
print("I'm printing")
}
func scrollViewDidScroll(scrollView: UIScrollView) {
print("I'm scrollin")
}
}
It compiles, but does not work. What am I doing wrong and what would be the right way to create a default implementation of expanded protocol?
What you want to do is the following:
protocol MyProtocol{
var myVar: NSString { get }
func myMethod()
}
protocol MyProtocol2{
var myVar2: NSString { get }
func myMethod2()
}
extension MyProtocol where Self: MyProtocol2 {
func myMethod() {
print("I'm printing ")
}
}
class anotherClass: MyProtocol, MyProtocol2 {
var myVar: NSString {
return "Yo"
}
var myVar2: NSString {
return "Yo2"
}
func myMethod2() {
print("I'm printing in myMethod2")
}
}
In the above code MyProtocol2 is equivalent to your UIScrollViewDelegate,
hence what you will do is:
protocol MyProtocol{
var myVar: NSString { get }
func myMethod()
}
extension MyProtocol where Self: UIScrollViewDelegate {
func myMethod() {
print("I'm printing")
}
}
class anotherClass: NSObject, MyProtocol, UIScrollViewDelegate {
var myVar: NSString {
return "Yo"
}
}
Notice that another class subclasses NSObject, this is because if you do not do so, you will get the error
anotherClass
does not conform to protocolNSObjectProtocol
This error is because UIScrollViewDelegate
itself is defined to be extending NSObjectProtocol
which is an objective-C protocol implemented by NSObject.
So make your class inherit from NSObject to conform to the NSObjectProtocol. Vanilla Swift classes do not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With