有没有办法允许Swift协议扩展访问实现所述协议的类中的某些内容,但是没有其他内容可以访问?

时间:2018-02-18 12:59:17

标签: swift protocols swift-protocols swift-extensions

我知道啰嗦的问题。一个例子可能更简单:

var thing = ThingDoer()
thing.doSomething()

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

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

protocol DoThings {
    func doSomething ()
}

extension DoThings显然无法访问sortOfPrivateDoSomething()。是否有任何方法可以以class ThingDoer: DoThings可以访问它的方式向extension DoThings添加函数或计算变量等等,但没有别的可以吗?

警告class ThingDoer: DoThingsextension DoThings不能位于同一个文件中。

感谢您的阅读。

附录

我不确定我是否会将以下内容视为一个可接受的答案,但我觉得我应该添加它,以显示我到目前为止设法找到最近的解决方案:

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 ()
}

2 个答案:

答案 0 :(得分:2)

如果在同一文件中声明类和协议扩展,则可以使用以下代码:

protocol DoThings {
    func doSomething ()
}

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

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

let thing = ThingDoer()
thing.doSomething()

答案 1 :(得分:0)

我认为您可以从在协议文件中编写类似的内容中受益

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