【问题标题】:candidate would match and infer 'T' = '[U]' if '[U]' conformed to 'Foo'如果 '[U]' 符合 'Foo',候选人将匹配并推断 'T' = '[U]'
【发布时间】: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 { }

【问题讨论】:

    标签: swift generics protocols


    【解决方案1】:

    Array 有这个扩展名:

    extension Array: Encodable where Element: Encodable …
    

    做同样的事情。

    extension Array: Foo where Element: Foo { }
    

    【讨论】:

    • 嘿@Jessy,如果Foo 有一些属性,那么数组也必须有这些属性,但数组不应该有。我该怎么办?
    • 考虑这两个东西是否真的有一些共同的协议。如果是这样,请制作一个新的,这代表了这一点。这似乎是一个新问题;随时链接到您将编写的另一个问题。
    猜你喜欢
    • 2014-11-30
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多