菜鸟教程小白 发表于 2022-12-12 11:34:11

ios - swift : Can you store functions as values in a dictionary?


                                            <p><p>我正在学习 Swift,我想知道是否可以将函数作为值存储在字典中。例如,类似于映射到函数的字符串的字典。</p>

<pre><code>var test : Dictionary = ()
</code></pre>

<p>我试过了,但编译器不喜欢它,说它需要一个 ','。如果可以创建这样的字典,我将如何创建它?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>你可以这样做 :) 编译器不会说一个字 :) </p>

<pre><code> typealias myFunc = (Double) -&gt; Double
var test3 : = ()
</code></pre>

<p>或</p>

<pre><code>typealias myFunc = (Double) -&gt; Double
var test3 : Dictionary = ()
</code></pre>

<p>最后,这是您可以向字典中添加一个的方法:)</p>

<pre><code>let mtfunc : myFunc ={
   print(&#34;Hi&#34;)
   return $0
}

test3[&#34;Sandeep&#34;] = mtfunc
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios -swift: Can you store functions as values in a dictionary?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/37748486/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/37748486/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - swift : Can you store functions as values in a dictionary?