Swift 3 Protocols
I first learned protocol-oriented-programming with Objective-C, and I was very pleased to see the Swift team emphasize this style.
But, at least at this writing at the end of 2016, I still run into problems when I use this style of programming in Swift.
Protocols (a.k.a. concepts) are not just bags of syntax; unless you can attach semantics to the operations, you can’t write useful generic algorithms against them. So we shouldn’t have
DefaultConstructible
for the same reason we shouldn’t have “Plusable” to represent something that lets you writex + x
.
Via Ole Begemann (tweet):
Yet, by conforming a type to
Equatable
you also guarantee that your implementation follows the protocol’s semantics, which are listed in its documentation.[…]
One problem with a generic
init()
requirement without additional context is thatT()
means very different things for differentT
[…][…]
The fourth argument against the
DefaultConstructible
protocol is that it clashes with Swift’s policy to not initialize values to “zero” or some other default. In contrast to many other languages, Swift doesn’t zero out memory for variables — the compiler forces the programmer to initialize every variable with an explicit value.
I’ve found these two papers particularly enlightening: