[swift-evolution] [Pitch] `let` in protocols

Karl Wagner razielim at gmail.com
Mon Jun 26 06:44:52 CDT 2017

> On 25. Jun 2017, at 22:13, Robert Bennett <rltbennett at icloud.com> wrote:
> For a concrete type, a partial initializer is a function that:
> Can set `let` instance variables
> May not refer to `self` in an rvalue
> Must set the same subset of instance variables regardless of the code path taken
> For a protocol, a partial initializer is simply a function that sets *any* subset of the instance variables. A protocol could provide a default implementation of one. In order for this `let` proposal to work, though, if a `let` variable is set in the protocol extension’s implementation of a (full) initializer, the protocol would need to provide at least one partial initializer that it does not provide an implementation for, so that a conforming type can fill in the gaps for all of the instance variables it defines that the protocol doesn’t require/know about. That way the compiler can have faith that a conforming type will be able to fully initialize itself with the default implementation of the required full initializer.

I’ll say again: I think you’re approaching this from the wrong angle. You want stronger guarantees about mutability of properties, but the answer is not to make protocols be more restrictive about how conformers are written.

What you are really asking for is the guarantee that some type which conforms to SomeProtocol has value-semantics. Once you have that guarantee, you know that you have a unique instance whose properties will only mutate if they are stored in a “var” property and you yourself mutate it.

For example, an Array’s “count” property is technically a computed property, but in a “let”-declared Array you can treat it as a “let” constant because Arrays have value semantics. Your guarantees about properties only being set in the initialiser would automatically be fulfilled without the need of any additional alternate initialisation patterns.

- Karl

More information about the swift-evolution mailing list