Scrungepipes
Scrungepipes

Reputation: 37581

How to override a protocol extension's default implementation of a func?

Is it possible to get the following code to make MyClass2:someFuncWithDefaultImplementation() invoked?

protocol MyProtocol : class {
    func someFuncWithDefaultImplementation()
    func someFunc()
    var  someInt:Int { get set }
}

extension MyProtocol {
    func someFuncWithDefaultImplementation() {
        someInt = 5
    }

    func someFunc() {
        someFuncWithDefaultImplementation()
    }
}

class MyClass :  MyProtocol {
    var someInt = 6
}

class MyClass2 : MyClass
{
    func someFuncWithDefaultImplementation()
    {
        someInt = 7
    }
}


...

  let class2 = MyClass2()
  class2.someFunc()

MyClass2 could have this method added:

func someFunc() {
       someFuncWithDefaultImplementation()
}

And it would work, but that is no use if MyProtocol:someFunc() is doing other stuff apart from calling someFuncWithDefaultImplementation() as it would just be code duplication.

Also doing this does not have the desired effect:

extension MyClass2 {
    func someFuncWithDefaultImplementation()
    {
        someInt = 7
    }
}

Upvotes: 5

Views: 6673

Answers (1)

nsleche
nsleche

Reputation: 108

The default implementations in the protocols are only called if the class that conforms to these protocols do not implement that method itself. The classes' methods override the default implementations of the protocols, not the other way around.

you could do like this:

import UIKit

protocol MyProtocol : class {
    func someFuncWithDefaultImplementation()
    func someFunc()
    var  someInt:Int { get set }
}

extension MyProtocol {
    func someFuncWithDefaultImplementation() {
        someInt = 5
    }

    func someFunc() {
        someFuncWithDefaultImplementation()
    }
}

class MyClass :  MyProtocol {
    var someInt = 6
}

class MyClass2 : MyProtocol
{
    var someInt: Int = 4
    func someFuncWithDefaultImplementation()
    {
        someInt = 7
    }

}


let class2 = MyClass2()
class2.someFunc()

or like this:

class MyClass :  MyProtocol {
    var someInt = 6
    func someFuncWithDefaultImplementation() {
        someInt = 8
    }
}

class MyClass2 : MyClass
{
    override func someFuncWithDefaultImplementation()
    {
        someInt = 7
    }
}

these were what i got with my tests, but you may find some better solution

Upvotes: 6

Related Questions