[SR-1581] Can not use protocol to fulfill associatedtype requirement where associatedType has protocol constraint Created: 21 May 2016  Updated: 23 Apr 2017  Resolved: 23 Apr 2017

Status: Resolved
Project: Swift
Component/s: Compiler

Type: Bug Priority: Medium
Reporter: Vishal Singh Assignee: Unassigned
Resolution: Duplicate Votes: 10
Labels: None

Issue Links:
Duplicate
duplicates SR-55 non-@objc protocol existentials do no... Open
Relates
relates to SR-55 non-@objc protocol existentials do no... Open
relates to SR-2020 Protocol composition doesn't conform ... Resolved

 Description   

The following code sample does not compile.

protocol Bar {   
}

protocol Buz: Bar {   
}

protocol Foo {
    associatedtype SomeType: Bar
    func someOperation(someType: SomeType)
}

struct Quack: Foo {
    func someOperation(someType: Buz) {
    }
}

It throws error:

Inferred type 'Buz' (by matching requirement 'someOperation') is invalid: does not conform to 'Bar'

I am not sure if we are only allowed to use a concrete type for associatedtype with protocol constraint. I don't see any reason for this restriction. If we remove the protocol constraint from associatedtype, then it compiles with no error.

Update 2016/12/12: I am using below workaround to tackle above bug. This seems more logical and makes me feel like its not a bug.

struct Quack<T>: Foo where T: Buz {
    func someOperation(someType: T) {
    }
}

// Usage
struct SomeBuz: Buz {}
let quack: Quack<SomeBuz> = Quack<SomeBuz>()
quack.someOperation(SomeBuz())

The reason this makes more sense to me is that the compiler now has more context on the actual type.



 Comments   
Comment by Jordan Rose [ 23 May 2016 ]

Protocols don't always "conform to themselves", but this configuration seems safe. Joe Groff?

Comment by Karl [ 27 Jun 2016 ]

+1 for this. The thing that we want to express is safe; if there are nuances with the current syntax we should devise a way to make it possible.

protocol A {}
protocol SubA : A {}

protocol B { associatedtype TypeOfA : A }

struct MyB : B {     // ERROR: `MyB` does not conform to `B`
	typealias TypeOfA = SubA
}
Generated at Mon Dec 10 22:09:55 CST 2018 using Jira 7.13.0#713000-sha1:fbf406879436de2f3fb1cfa09c7fa556fb79615a.