菜鸟教程小白 发表于 2022-12-11 20:22:06

ios - Swift泛型类参数实现另一个参数


                                            <p><p>我想在 Swift 中实现一个带有两个参数的泛型类。一个必需的约束是第一个参数是协议(protocol),第二个参数必须实现该协议(protocol)。</p>

<p>代码:</p>

<pre><code>protocol Protocol {}

class Generic&lt;T: Protocol, U&gt;where U: T {

}
</code></pre>

<p>编译器错误提示:</p>

<blockquote>
<p>error: type &#39;U&#39; constrained to non-protocol, non-class type &#39;T&#39;</p>
</blockquote>

<p>但这不是真的,因为 <code>T</code> 是一个协议(protocol)。</p>

<p>你知道如何实现它吗?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>我<em>认为</em>你想要的是</p>

<pre><code>protocol Protocol {}
class Generic&lt;T: Protocol&gt; {
    init(type: T.Type, instance: T) {

    }
}
</code></pre>

<p>但是用例可以帮助我们了解您想要实现的目标...</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - Swift泛型类参数实现另一个参数,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/51375864/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/51375864/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - Swift泛型类参数实现另一个参数