菜鸟教程小白 发表于 2022-12-11 19:07:01

ios - 在 Swift 中使用 Objective-C block 时保留参数类型


                                            <p><p>我刚刚开始在 Swift 而不是 Objective-c 中实现我们的一些新功能,到目前为止一切正常,但让我感到困惑的一件事是如何在 Swift 中正确使用 Obj-Cblock 。 </p>

<p>在我的 Obj-C 类中,我定义了一个 block ,用于处理对我们 API 的调用的 HTTP 响应:</p>

<pre><code>typedef void(^CCAPIClientRequestCompletionBlock)(id response, NSArray *messages, NSDictionary *metaData, NSError *error);
</code></pre>

<p>这用于以下方法:</p>

<pre><code>-(void)createMeetingWithUsers:(NSArray *)users subject:(NSString *)subject andDescription:(NSString *)description withCompletionBlock:(CCAPIClientRequestCompletionBlock)completionBlock;
</code></pre>

<p>我现在正在编写一个 API 客户端来访问我们在 Swift 中的 API 的一个新领域,并尝试将 block 重用为闭包。下面的代码构建并运行:</p>

<pre><code>apiClient.createMeeting(withUsers: userIds, subject: subject, andDescription: description) { (response, messages, metaData, error) -&gt; Void in

    }
</code></pre>

<p>但我希望能够保留参数类型,并认为我应该能够执行以下操作:</p>

<pre><code>apiClient.createMeeting(withUsers: userIds, subject: subject, andDescription: description) { (response:Any?, messages:, metaData:, error:NSError) -&gt; Void in

    }
</code></pre>

<p>但是当我尝试这个时,我得到一个错误:</p>

<pre><code>Cannot convert value of type &#39;(Any?, , , NSError) -&gt; Void&#39; to expected argument type &#39;CCAPIClientRequestCompletionBlock!&#39;
</code></pre>

<p>我在这里错过了什么?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您应该将所有类型更改为可选项并将 <code>NSError</code> 更改为 <code>Error?</code>:</p>

<pre><code>apiClient.createMeeting(withUsers: userIds, subject: subject, andDescription: description) { (response:Any?, messages:?, metaData:?, error:Error?) -&gt; Void in
   //TODO
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 在 Swift 中使用 Objective-Cblock 时保留参数类型,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/42510557/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/42510557/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 在 Swift 中使用 Objective-C block 时保留参数类型