Example from the official documentation contains error

In the official documentation for this link https://docs.swift.org/swift-book/LanguageGuide/Generics.html .
Collecting all the code from the section 'Associated Types in Action' to section ' Generic Where Clauses', and testing code in playground, i got error's.

The error occurs because Element from struct Stack, does not match protocol Container, because associatedtype Item: Equatable.
So, Element from struct Stack, must be <Element: Equatable>

Thanks for pointing this out — I'm the writer currently working on "The Swift Programming Language", so I can help fix that.

If you still have the code you got the error with, can you post that? When I compile and test the code from that chapter, I don't see the same error you mention.

It's also worth noting that the associated type from a protocol doesn't have to have the same name as the struct's generic type. In this example, struct Stack<Element> has a generic Element type that satisfies the requirement from protocol Container for an Item type. For example, Container requires that its append(_:) function accepts an item and that its subscript returns an item. In the case of Stack, that item is Element.

i got errors because in section 'Adding Constraints to an Associated Type' i changed conditions from

associatedtype Item

to

associatedtype Item: Equatable

. And then if you use the code from other sections described above, it will cause errors.
The 'Adding Constraints to an Associated Type' section says:

You can add type constraints to an associated type in a protocol to require that conforming types satisfy those constraints.

the official documentation does not say which code we should use next, from section 'Associated Types in Action' with his code:

1.protocol Container {
2. associatedtype Item
3. mutating func append(_ item: Item)
4. var count: Int { get }
5. subscript(i: Int) -> Item { get }
6. }

Or we should use, this code, from section 'Adding Constraints to an Associated Type':

  1. protocol Container {
  2. associatedtype Item: Equatable
  3. mutating func append(_ item: Item)
  4. var count: Int { get }
  5. subscript(i: Int) -> Item { get }
  6. }

Perhaps for beginners this is not entirely obvious.

p.s. sorry for my English

The code i am using:
Code from section 'Associated Types in Action' to section 'Generic Where Clauses'

my answer is below

Terms of Service

Privacy Policy

Cookie Policy