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

Satoshi Nakagawa psychs at limechat.net
Tue May 2 03:57:30 CDT 2017


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170502/386b5ee1/attachment.html>


More information about the swift-users mailing list