0

Long-winded question I know. An example is probably simpler:

var thing = ThingDoer()
thing.doSomething()

class ThingDoer: DoThings {
    private func sortOfPrivateDoSomething () {}
}

extension DoThings {
    func doSomething () {
        self.sortOfPrivateDoSomething()
    }
}

protocol DoThings {
    func doSomething ()
}

extension DoThings clearly cannot access sortOfPrivateDoSomething(). Is there any way one can add a func - or a computed var, etc. - to class ThingDoer: DoThings in such a way that extension DoThings could access it, but nothing else could?

caveat: class ThingDoer: DoThings and extension DoThings cannot be in the same file.

Thank you for reading.


Appendix

I am not sure I would posit the following as an acceptable answer, but I feel I should add it, to show the nearest I have managed to get to a solution thus far:

var thing = ThingDoer()
thing.doSomething()

class ThingDoer: DoThings {
    fileprivate var someOtherThing: SomeSortOfOtherThing
    init () { someOtherThing = SomeSortOfOtherThing() }
}

extension DoThings {
    fileprivate var _someOtherThing: SomeSortOfOtherThing? {
        let selfReflection = Mirror( reflecting: self )
        for ( _, child ) in selfReflection.children.enumerated() {
            if child.value is SomeSortOfOtherThing { return ( child.value as! SomeSortOfOtherThing ) }
        }
        return nil
    }

    func doSomething () {
        guard var scopedSomeOtherThing = _someOtherThing else { return }
        scopedSomeOtherThing.doSomeOtherThing()
    }
}

protocol DoThings {
    func doSomething ()
}
Joseph Beuys' Mum
  • 2,395
  • 2
  • 24
  • 50

2 Answers2

2

If you declare your class and protocol extension in the same file, you can use the following code:

protocol DoThings {
    func doSomething ()
}

class ThingDoer: DoThings {
    fileprivate func sortOfPrivateDoSomething () {}
}

extension DoThings where Self: ThingDoer {
    func doSomething () {
        sortOfPrivateDoSomething()
    }
}

let thing = ThingDoer()
thing.doSomething()
0

I think you could benefit from writing something like this in your protocol file

extension DoThings where Self: ThingDoer {
    func doSomething () {
        sortOfPrivateDoSomething()
    }
    private func sortOfPrivateDoSomething () {
    }
}
Ahmed Elashker
  • 1,001
  • 1
  • 8
  • 17