Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift extension that conforms to protocol

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'

like image 830
Errortype520 Avatar asked Jul 23 '14 01:07

Errortype520


People also ask

What is Swift protocol extension?

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.

Can we use protocol with structure in Swift?

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.

Can we extend protocol?

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.)


2 Answers

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
    }
}
like image 144
kurtn718 Avatar answered Oct 08 '22 07:10

kurtn718


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

like image 43
Anup Avatar answered Oct 08 '22 09:10

Anup