gpt4 book ai didi

从函数返回多个值时出现 Swift 错误

转载 作者:可可西里 更新时间:2023-11-01 00:39:12 25 4
gpt4 key购买 nike

我不明白我做错了什么


我有一个加载帖子及其评论的应用程序。 View Controller 从另一个文件请求一个函数,该函数返回(响应?评论?)

我得到一个错误:

Initializer for conditional binding must have Optional type, not '(ActionResult?, [PostComment]?)'

对于行

if let (response, comments) = (response, comments )

我做错了什么?

评论 View Controller

postComments.loadCommentForPost(id: postId) { (response, comments) in
// ERROR here: Initializer for conditional binding must have Optional type, not '(ActionResult?, [WorldMessageComment]?)'
if let (response, comments) = (response, comments ) {
if response!.success == 1 {
DispatchQueue.main.async(execute: {() -> Void in
self.comments = comments!
self.tableView.reloadData()
})
} else {
DispatchQueue.main.async(execute: {() -> Void in
self.handleResponses.displayError(title: response!.title, message: response!.message)
})
}
}
}

评论函数

func loadCommentsForPost(id: Int, completion: @escaping ((ActionResult?), [PostComment]?)->()){

// downloading the data and then

let comments : [PostComment] = ...

// Succesful
return completion((ActionResult(success: 1, title: responseTitle, message: responseMessage)), comments)

}

最佳答案

问题在行中:

if let (response, comments) = (response, comments ) {

你基本上做的是在赋值的右侧创建一个新的非可选元组(有两个可选组件),所以编译器提示你不能使用 if let with非可选类型。

您实际上可以认为 loadCommentsForPost 返回的元组已经在回调的参数中“拆分”,因此您可以分别处理 responsecomments

postComments.loadCommentForPost(id: postId) { response, comments in
if let response = response, let comments = comments {
if response.success == 1 {
...

关于从函数返回多个值时出现 Swift 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49970139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com