Reputation: 363
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'
Upvotes: 14
Views: 18654
Reputation: 751
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
}
}
Upvotes: 21
Reputation: 123
//**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..!
Upvotes: 10