gpt4 book ai didi

arrays - 如何快速返回函数中的自定义对象数组

转载 作者:搜寻专家 更新时间:2023-10-31 22:16:21 25 4
gpt4 key购买 nike

我无法快速从函数返回自定义对象数组。我总是收到 [(custon object)] is not convertable to '()' 错误消息。我认为我违反了一些快速协议(protocol)。下面是我的代码。请让我知道我违反了什么。

import Foundation

class DataSet {
var settings:Settings!
var service:PostService!
var currentBrand:Brand!

init(){
self.settings = Settings()
self.service = PostService()
}

func loadComments(id:Int) -> [CommentsList]{
service.apiCallToGet(settings.getComments(id), {
(response) in
var commentsList = [CommentsList]()
if let data = response["data"] as? NSDictionary {
if let comments = data["comments"] as? NSArray{
for item in comments {
if let comment = item as? NSDictionary{
var rating = comment["rating"]! as Int
var name = comment["device"]!["username"]! as NSString
var text = comment["text"]! as NSString
var Obj_comment = CommentsList(rating: rating, name: name, text: text)
commentsList.append(Obj_comment)
}
}
}
}

return commentsList //This line shows error as : "[(CommentsList)] is not convertable to '()'"
})
}
}

最佳答案

您的返回语句位于 Web 服务的完成 block 内,它不返回任何内容 () - 这就是错误的含义。

作为异步网络调用包装器的方法不能返回值,因为您必须阻塞直到网络调用完成。您的 loadComments 方法应该采用一个完成 block 参数,该参数采用 [CommentsList] 作为参数:

func loadComments(id: Int, completion:(comments:[CommentsList])->Void) {
// existing code

然后,将您的返回语句替换为

completion(comments:commentsList)

关于arrays - 如何快速返回函数中的自定义对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27957302/

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