[swift-users] How to use a protocol to infer a generic type with constraints

Satoshi Nakagawa psychs at limechat.net
Tue May 2 04:08:09 CDT 2017


Hi Slava,

Thanks for your quick response!

I see. That's in line with what I can read from the Type Constraint Syntax
section in the official Swift book.

Satoshi


On Tue, May 2, 2017 at 1:59 AM, Slava Pestov <spestov at apple.com> wrote:

> Hi Satoshi,
>
> Protocols do not conform to themselves. Only concrete types can conform to
> protocols in the current implementation of Swift.
>
> Slava
>
> > On May 2, 2017, at 1:57 AM, Satoshi Nakagawa via swift-users <
> swift-users at swift.org> wrote:
> >
> > Hi,
> >
> > I got a build error "Generic parameter 'T' could not be inferred" for
> the following code.
> >
> > Can anyone explain why we can't use a protocol to infer the generic type
> T?
> >
> > class Emitter {
> >     func emit<T: Emittable>() -> T {
> >         ...
> >     }
> > }
> >
> > protocol Emittable {}
> > protocol Subemittable: Emitable {}
> >
> > class ConcreteEmittable: Subemittable {}
> >
> > func testCode() {
> >     let emitter = Emitter()
> >
> >     // Error: Generic parameter 'T' could not be inferred
> >     let _: Emittable = emitter.emit()
> >
> >     // Error: Generic parameter 'T' could not be inferred
> >     let _: Subemittable = emitter.emit()
> >
> >     // This works
> >     let _: ConcreteEmittable = emitter.emit()
> > }
> >
> > Thanks,
> > Satoshi
> >
> > _______________________________________________
> > swift-users mailing list
> > swift-users at swift.org
> > https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170502/39de4656/attachment.html>


More information about the swift-users mailing list