ios - 关联类型 Swift 3
<p><p>我正在尝试理解 <strong>Swift</strong> 中的泛型文化,所以我写了一个小例子。但它不编译。 </p>
<p>错误:<strong>无法推断通用参数“P”</strong>
我做错了,我无法理解。</p>
<pre><code>protocol Protocol_1 {
associatedtype T
}
protocol Protocol_A {}
struct SomeStruct_2: Protocol_A {}
struct SomeStruct_1: Protocol_1 {
typealias T = Protocol_A
}
let struct1 = SomeStruct_1()
testFunction(t: struct1) // *Generic parameter 'P' could not be inferred*
func testFunction<P: Protocol_1>(t: P) where P.T : Protocol_A {
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>testFunction中的P.T不符合Protocol_A,但你可以检查它是否等于Protocol_A。</p>
<pre><code>func testFunction<P: Protocol_1>(t: P) where P.T == Protocol_A {
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 关联类型 Swift 3,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/40783044/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/40783044/
</a>
</p>
页:
[1]