[swift-evolution] Pitch: Allow generic functions to fulfill non-generic protocol requirements

Xiaodi Wu xiaodi.wu at gmail.com
Wed May 24 19:11:34 CDT 2017


On Wed, May 24, 2017 at 3:32 PM, David Sweeris via swift-evolution <
swift-evolution at swift.org> wrote:

> So, I’m working on a type, and would like to make it conform to
> `ExpressibleByArrayLiteral`. The thing is, I don’t actually care what type
> `Element` is as long as it conforms to `FixedWidthInteger` and
> `UnsignedInteger`. I tried writing this:
>   public init <U: FixedWidthInteger & UnsignedInteger> (arrayLiteral
> elements: U...) { … }
> But Xcode says my type doesn’t conform to `ExpressibleByArrayLiteral`
> unless I add an init that takes a concrete type:
>   public init(arrayLiteral elements: UInt...) { … }
>
> Does anyone else think the generic init should to be able to satisfy
> `ExpressibleByArrayLiteral` (especially since `UInt` meets the conformance
> requirements)?
>

Your type needs to be generic.

```
struct S<T : UnsignedInteger & FixedWidthInteger> {
  let x: [T]
}

extension S : ExpressibleByArrayLiteral {
  init(arrayLiteral: T...) {
    self.x = arrayLiteral
  }
}
```

I suspect that the compiler is complaining because the generic init
> function implies that the `Element` associated type is a generic
> constraint, rather than a concrete type (which maybe makes this related to
> generic protocols?). I think that’s only an issue because of the current
> ExpressibleBy*Literal protocols’ reliance on associated types to specify
> the relevant init’s signature, though. If the protocols (or literal system)
> could be re-architected so they don't need those associated types, it might
> make implementing this easier. I don’t know how much work either approach
> would be. Nor am I sure if it’d be better for this to be a use-case for
> another proposal instead of its own thing.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170524/9e02afb6/attachment.html>


More information about the swift-evolution mailing list