0

Is it possible to write an extension based on a protocol in Swift?

I know I can use a base class but I would like not to.

protocol SomeProtocol {
    var numbers: [Int] { get set }
}


extentension T: SomeProtocol {
    func sumarize() -> Int {
        return self.numbers.reduce(0, +)
    }
}
Konrad77
  • 2,515
  • 1
  • 19
  • 36
  • 1
    I think, my answer is not answering your question. Maybe what you looking for is http://stackoverflow.com/questions/24047164/extension-of-constructed-generic-type-in-swift – rintaro Oct 17 '14 at 09:01

2 Answers2

0

I don't think this is supported. As you can see in the official Apple documentation:-

https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Extensions.html#//apple_ref/doc/uid/TP40014097-CH24-XID_231

Extensions add new functionality to an existing class, structure, or enumeration type.

Unfortunately protocols do not seem to be covered here

Rajeev Bhatia
  • 2,974
  • 1
  • 21
  • 29
0

You can. In fact, many of builtin types are implemented with that. like:

extension Array : Printable, DebugPrintable {
    var description: String { get }
    var debugDescription: String { get }
}

I mean, you can implement a protocol in a extension. see this document

In your case, implementing var numbers:[Int] in extentension T: SomeProtocol { ... } is your responsibility. like:

protocol SomeProtocol {
    var numbers: [Int] { get set }
}

struct T {
    private var _numbers:[Int] = [1,2,3]
}

extension T:SomeProtocol {
    var numbers:[Int] {
        get {
            return self._numbers
        }
        set(newVal) {
            self._numbers = newVal
        }
    }

    func sumarize() -> Int {
        return self.numbers.reduce(0, +)
    }
}
rintaro
  • 51,423
  • 14
  • 131
  • 139