Fast extensions to structures make private initialization protection impossible

In Swift, you can prevent the initialization of an object directly by making the initializer private. You can do this with the Factory template.

But if you create an extension, you can provide another initializer and compile it. It doesn't matter if the extension is in the same file or not. This can have serious consequences if your Factory method does some data validation, for example.

Am I missing something in my personal affairs? It seems very bad. Can I prevent this?

struct Foo { let data: Int // factory method static func makeFoo(data: Int) -> Foo { return Foo(data: data) } // private init with data validation private init(data: Int) { guard data < 100 else { fatalError("Foo should only have values under 100") } self.data = data } } extension Foo { init(someData: Int) { // This bypasses the data validation and puts Foo into an invalid state. self.data = someData } } 
+5
source share
1 answer

According to the comments above, this will be banned in Swift 5.

0
source

Source: https://habr.com/ru/post/1273093/


All Articles