I am having trouble creating an extension in Swift that conforms to a protocol.
In Objective-C I could create a category that conformed to a protocol:
SomeProtocol.h
@protocol SomeProtocol
...
@end
UIView+CategoryName
#import SomeProtocol.h
@interface UIView (CategoryName) <SomeProtocol>
...
@end
I am trying to achieve the same with a Swift Extension
SomeProtocol.swift
protocol SomeProtocol {
...
}
UIView Extension
import UIKit
extension UIView : SomeProtocol {
...
}
I receive the following compiler error:
Type 'UIView' does not conform to protocol 'SomeProtocol'
In Swift, you can even extend a protocol to provide implementations of its requirements or add additional functionality that conforming types can take advantage of. For more details, see Protocol Extensions. Note. Extensions can add new functionality to a type, but they can't override existing functionality.
In Swift, protocols contain multiple abstract members. Classes, structs and enums can conform to multiple protocols and the conformance relationship can be established retroactively. All that enables some designs that aren't easily expressible in Swift using subclassing.
Protocol extensions are different. You cannot “extend” a protocol because by definition a protocol doesn't have an implementation - so nothing to extend. (You could say that we “extend a protocol WITH some functionality”, but even an extended protocol is not something we can apply a function to.)
Please double check in your extension that you've implemented all of the methods defined in the protocol. If function a is not implemented, then one will get the compiler error that you listed.
protocol SomeProtocol {
func a()
}
extension UIView : SomeProtocol {
func a() {
// some code
}
}
//**Create a Protocol:**
protocol ExampleProtocol {
var simpleDescription: String { get }
func adjust()-> String
}
//**Create a simple Class:**
class SimpleClass {
}
//**Create an extension:**
extension SimpleClass: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
func adjust()-> String {
return "Extension that conforms to a protocol"
}
}
var obj = SimpleClass() //Create an instance of a class
println(obj.adjust()) //Access and print the method of extension using class instance(obj)
Result: Extension that conforms to a protocol
Hope it helps..!
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