15
votes

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'

2
did you implement the methods in the protocol?Bryan Chen

2 Answers

20
votes

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
    }
}
10
votes
//**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..!