2

How can I implement class-internal protocols in Swift?

The problem is that

class C {
    private protocol P {
        func aFunction()
    }

    private class D: P {
        func aFunction() {
            //...
        }
    }
}

results in the error

Declaration is only valid at file scope

Any ideas for bypassing the problem?

Exclusion: I do not refer to class-only protocols, which is possible, of course.

4

1 回答 1

4

Access control in swift is file based. I do not believe you can define a protocol within a class, but you can include it within the same document.

private protocol P {
    func aFunction()
}

class C {
    private class D: P {
        private func aFunction() {
            //...
        }
    }
}

Of course this does not mean that classes that inherit from class C can use protocol P.

To my knowledge Swift does not support inheritance based access control.

于 2015-12-15T16:05:02.693 回答