iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🈁

[Swift] Difference Between Protocols with Primary Associated Types and "Generic Protocols"

に公開

The Primary Associated Types feature introduced in Swift 5.7 enabled the following notation.

// A function that takes any collection (Element type is not specified)
func foo<T: Collection>(collection: T)

// A function that takes any collection of Int
func foo<T: Collection<Int>>(collection: T)

var collection: any Collection= [1, 2, 3]
print(collection.first!)   // The type of first becomes Any?

var intCollection: any Collection<Int> = [1, 2, 3]
print(intCollection.first!) // The type of first is determined as Int?

This notation like Collection<Int> was proposed and introduced in SE-0346 as a "lightweight syntax for specifying same-type requirements on primary associated types."

https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md

By the way, this feature is sometimes introduced as "generic protocols." Depending on what you mean by the word "generic," this is not a very accurate explanation for the primary associated type syntax.

In this article, I will explain the difference between "generic protocols" and "protocols with primary associated types."

What is "Generic"?

As I mentioned at the beginning, the meaning of the word "generic" is the first issue, but in Swift, it can be summarized as "sharing an implementation across multiple types through the use of type parameters." For example, the following is a generic "swap."

func swap<T>(lhs: inout T, rhs: inout T) {
    (lhs, rhs) = (rhs, lhs)
}

In this swap, the type parameter T is automatically inferred from the argument types, and it can be used like this:

var a = 0
var b = 1
swap(&a, &b)
print(a, b) // 1, 0

Generic functions work with multiple types. For example, the following use cases are all perfectly fine:

var a = true, b = false
swap(&a, &b)

var a = "Hi", b = "Swift"
swap(&a, &b)

var a = [0, 1, 2], b = [2, 1, 0]
swap(&a, &b)

As many of you likely know, you can add constraints to type parameters. In the following example, since T is constrained by the Equatable protocol, lhs == rhs can always be executed.

func equal<T: Equatable>(lhs: T, rhs: T) -> Bool {
    return lhs == rhs
}

In this way, we can consider that generics is the use of type parameters.

Associated Types and Type Aliases in Protocols

Next, let's review associated types. Associated types are defined within a protocol and declare a type that should be implemented as a nested type in the type that adopts the protocol.

protocol List {
    // Associated type
    associatedtype Element
}

To satisfy the requirement of an associated type, it is sufficient as long as T.Element exists. Therefore, you can implement it as follows:

struct IntList: List {
    typealias Element = Int
}

struct MyList: List {
    struct Element {}
}

struct GenericList<Element>: List {
    typealias Element = Element
}

The important point is that just because there is an associated type requirement doesn't mean it must be expressed as a type parameter. In the IntList example, Element is specified with an alias, and in MyList, the Element type is defined internally. In every example, .Element exists, so the constraint is satisfied.
Furthermore, a type parameter cannot directly satisfy an associated type requirement. This is because the type parameters of a generic type cannot be accessed from the outside unless they are explicitly exposed via typealias.
For example, the following will result in an error:

struct Foo<T> {}
print(Foo<Int>.T.self)  // error

The keyword associatedtype is long and might be a bit startling at first, but what it means is simple.

Primary Associated Types

Now, let's finally talk about Primary Associated Types. Primary Associated Types are a feature for representing particularly important associated types within a protocol using a special syntax. Any protocol can have zero or more primary associated types. I won't discuss here "how to decide which associated type should be the primary one," but basically, you should specify the types you frequently want to constrain.

Let's start by looking at the definition. For example, in a List protocol, the Element associated type, which represents the element type, can be made a primary associated type.

// Here, Element is declared to be treated as a primary associated type
protocol List<Element> {
    // The existence of the associated type is declared here
    associatedtype Element
}

One thing to be careful about here is that the declaration of associatedtype Element is absolutely necessary. The order of interpretation is as follows:

  1. Declare an associated type named Element.
  2. By declaring the protocol as List<Element>, you explicitly indicate that this is a primary associated type.

In fact, for example, the following implementation results in a compilation error:

// error: an associated type named 'Element' must be declared in the protocol 'List' or a protocol it inherits
protocol List<Element> {
}

As stated here, <Element> is not a type parameter; its role is merely to declare a previously declared associated type as being primary.

Because of this, the following implementation also results in an error:

// error: expected '>' to complete primary associated type list
protocol List<Element: Equatable> {
    associatedtype Element
}

To reiterate, the <...> part after List is a "primary associated type list" and not a declaration of type parameters. The type declared here is already declared as associatedtype Element, and you cannot apply additional constraints within the primary associated type list.

Note that it might feel a bit strange for the reading order to be reversed, but this is common in protocol declarations. For example, the following is a valid implementation:

protocol List where Element: Equatable {
    associatedtype Element
}

This implementation should be read as follows:

  1. Declare an associated type named Element.
  2. Apply a constraint to Element using where Element: Equatable.

Now, with the explanation so far, I believe you understand why the declaration of primary associated types is different from generics.

The expression <T> in generics is a syntax for "introducing a new type parameter." In contrast, the declaration of primary associated types merely states that "since these associated types are primary, they can be written as <T>."

In this way, even though the same <T> notation is used, its meaning is entirely different.

Generic Protocols

Then, if there really were such a thing as a "generic protocol," how would it behave? Actually, this point was widely discussed during the introduction of primary associated types. This is because there was a concern that the syntax for primary associated types might "steal" the syntax for "generic protocols" that could be introduced in the future.

"Generic protocols" are protocols where implementations are shared through type parameters. In the proposal for the introduction of primary associated types, the following is given as an example of a "generic protocol":

protocol GenericConvertibleTo<Other> {
  static func convert(_: Self) -> Other
}

extension String : GenericConvertibleTo<Int> {
  static func convert(_: String) -> Int { 0 }
}

extension String : GenericConvertibleTo<Double> {
  static func convert(_: String) -> Double { 0 }
}

The important difference to note is that Other is not an associated type. For example, a protocol like GenericConvertibleTo<Int> is actually a protocol like the one below. Clearly, there is no associated type here[1].

protocol ConvertibleToInt {
  static func convert(_: Self) -> Int
}

Because of this, String can conform to both GenericConvertibleTo<Int> and GenericConvertibleTo<Double> simultaneously.

What if Other were a primary associated type? In that case, the protocol definition would look like this:

protocol ConvertibleTo<Other> {
  associatedtype Other
  static func convert(_: Self) -> Other
}

Actually, the following would result in an error[2],

extension String : ConvertibleTo<Int> {
  static func convert(_: String) -> Int { 0 }
}

so you would have to write it as follows... but this, of course, would also result in an error.

extension String : ConvertibleTo {
  typealias Other = Int
  static func convert(_: String) -> Int { 0 }
}

// Error: Redundant conformance of 'String' to protocol 'ConvertibleTo'
extension String : ConvertibleTo {
  // Error: Invalid redeclaration of 'Other'
  typealias Other = Double
  static func convert(_: String) -> Double { 0 }
}

Thus, when Other is an associated type, it's impossible for String to conform to both ConvertibleTo<Int> and ConvertibleTo<Double> at the same time. This is a major difference between generic protocols and primary associated types.

Another major difference is that generic protocols cannot be used as a protocol without <Other>. For example, in the case of GenericConvertibleTo above, the following would result in an error. Since the type parameter <Other> is not specified, GenericConvertibleTo is not a protocol.

func take<T: GenericConvertibleTo>(value: T) {
    // Results in an error
}

This is the same phenomenon as Array itself not being treatable as a type when no type parameter is specified.

On the other hand, protocols with primary associated types are different. There is no problem using ConvertibleTo as follows:

func take<T: ConvertibleTo>(value: T) {
    // T.Other is an associated type
}

In this way, a protocol with primary associated types is ultimately just "one protocol" and does not behave in the way that would be expected if "generic protocols" existed.

In other words, primary associated types only changed the notation for the caller; it doesn't mean the protocol has acquired some new kind of functionality.

In fact, while things like Collection suddenly became Collection<Element> after Swift 5.7, existing code using Collection didn't suddenly break. This is because the requirements for Collection haven't changed.

Will "Generic Protocols" be introduced?

As we've seen, "generic protocols" don't exist in current Swift, but they have been introduced in Rust as "generic traits," so it's not a feature that no language adopts.

However, the introduction of this feature to Swift has been evaluated negatively. During the first review of SE-0346, which introduced the primary associated type syntax, conflict with generic protocol syntax was raised as an issue, but the core team concluded as follows:

We do not think that "generic protocols" are the right way to model arbitrary relationships between multiple types, and so we are not concerned about taking the generic-argument syntax away from that future direction.

Based on this, it's safe to assume that "generic protocols" will not be introduced in Swift in the future.

Summary

In this article, I have explained the differences between generic protocols and protocols with primary associated types.

While the differences were the main theme this time, the behavior of "generic protocols"—which will not be introduced—is not that important.
In practice, what's more important is what kind of expectations to have regarding the behavior of primary associated types. If you think of the <T> part of a primary associated type as a type parameter, it might lead to misunderstandings, such as thinking that the <T> in Collection<T> must always be written.

The primary associated type syntax achieves an intuitive notation like Collection<T>, but it is a feature in a slightly complex position that, upon careful consideration, is quite different from generics. Let's understand it correctly and use it wisely.

脚注
  1. Strictly speaking, Self is an implicit associated type. ↩︎

  2. I think this might be a somewhat artificial constraint. This is because interpreting code like extension String : ConvertibleTo<Int> as extension String : ConvertibleTo { typealias Other = Int } wouldn't cause any particular problems. In fact, since there is a mention in the proposal, it might be a bug. ↩︎

Discussion