候选人将匹配并推断"T"="[U]",如果"[U]"符合"Foo"



如果代码是这样的,则会显示错误,编译器无法推断T = [U]

protocol Foo { }
protocol Bar {
associatedtype T: Foo
var type: T { get }
}
struct Baz<U: Foo> {
let type: [U]
}
extension Baz: Bar { }
/* error message
error: Demo.playground:14:1: error: type 'Baz<U>' does not conform to protocol 'Bar'
extension Baz: Bar { }
^
Demo.playground:6:20: note: unable to infer associated type 'T' for protocol 'Bar'
associatedtype T: Foo
^
Demo.playground:11:9: note: candidate would match and infer 'T' = '[U]' if '[U]' conformed to 'Foo'
let type: [U]
^
*/

但是用Decodable代替Foo,编译器可以推断出T = [U],为什么?

// protocol Foo { }
protocol Bar {
associatedtype T: Decodable
var type: T { get }
}
struct Baz<U: Decodable> {
let type: [U]
}
extension Baz: Bar { }

Array具有以下扩展:

extension Array: Encodable where Element: Encodable …

做同样的事。

extension Array: Foo where Element: Foo { }

最新更新