【发布时间】:2020-11-23 06:53:09
【问题描述】:
如果这样的代码,错误显示和编译器无法推断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]
^
*/
但是将Foo替换成Decodable,编译器可以推断出T = [U],为什么?
// protocol Foo { }
protocol Bar {
associatedtype T: Decodable
var type: T { get }
}
struct Baz<U: Decodable> {
let type: [U]
}
extension Baz: Bar { }
【问题讨论】: