[swift-users] Associatedtype Naming Conventions

Dave Abrahams dabrahams at apple.com
Tue Jun 6 19:00:04 CDT 2017


on Tue Jun 06 2017, Karl Wagner <razielim-AT-gmail.com> wrote:

>> On 7. Jun 2017, at 00:25, Dave Abrahams via swift-users <swift-users at swift.org> wrote:
>> 
>> 
>> on Wed May 31 2017, Steven Brunwasser <swift-users-AT-swift.org
> <http://swift-users-at-swift.org/>> wrote:
>> 
>
>>> Yes, I understand this. I was just wondering if there was a naming
>>> convention I should use to differentiate them.
>> 
>> I would try to find something more specific and descriptive than
>> “Container” and “Element” if you think there's a chance they would ever
>> arise as associated types of the same type but with distinct identity.
>> 
>> Another possibility, if you think that might be about to happen, is that
>> you're using conformance when you should use aggregation.  For example,
>> an Int has everything it needs to be a Sequence and/or Iterator (n to
>> infinity), a Collection (of numbers from zero to its bitWidth), etc.,
>> but *should* it conform to those protocols?  IMO probably not.  If you
>> find yourself hard pressed to describe what something *is* in a few
>> words, it may be conforming to too many protocols.
>
> Additionally, I find that when a type is representable in multiple
> overlapping ways (where “overlapping” is meant quite broadly), it can
> be good to create wrappers for those conformances.

Jah, that's what I meant to imply, but failed to spell out.  Thanks for
clarifying, Karl!

>
>
> For example, you might try:
>
> Struct MyThing {
> }
>
> extension MyThing {
>
>     var foo: Foo { return MyThing.FooWrapper(self) }
>     var bar: Bar { return MyThing.BarWrapper(self)  }
>
>     struct FooWrapper: Foo {
>         let base: MyThing
>         init(_ wrapping: MyThing) { self.base = wrapping }
>
>         // Implement ‘Foo’ using data from ‘base’.
>     }
> }
>
> let something = MyThing()
>
> takesAFoo(something.foo)
> takesABar(something.bar)
>
> This is analogous to how String is represented — the data is stored once, and there are multiple
> Collection conformances which interpret the data in different ways (as graphemes, or as a collection
> of non-character-boundary code-units in various encodings).

-- 
-Dave


More information about the swift-users mailing list