candidate 将匹配并推断 'T' = '[U]' 如果 '[U]' 符合 'Foo'
candidate would match and infer 'T' = '[U]' if '[U]' conformed to '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]
^
*/
但是将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 { }
Array
有此扩展名:
extension Array: Encodable where Element: Encodable …
照样做。
extension Array: Foo where Element: 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]
^
*/
但是将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 { }
Array
有此扩展名:
extension Array: Encodable where Element: Encodable …
照样做。
extension Array: Foo where Element: Foo { }