TruMan1 TruMan1 - 1 year ago 79
Swift Question

Restrict extensions on a type in Swift?

I have a specific class in Swift that I would like to restrict extensions from being created. I tried adding the

final
keyword, but it does not restrict extensions:

final class MyTest {
func testFunc() {}
}

extension MyTest {
func testFunc2() {}
}

let test = MyTest()
test.testFunc2()


Is this possible?

Answer Source

You cannot prevent someone from adding an extension to your class.

The final modifier only prevents subclassing. Other developers will always be able to add extensions.

Make your stuff private

However you can restrict what others can do with extensions.

E.g. a private property or method won't be visibile from other source files. So other users won't be able to use them with their extensions.