如何 return swift 中函数中的自定义对象数组

How to return a custom array of objects in a function in swift

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

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 '()'"
        })
    }
}

您的 return 语句位于 Web 服务的完成块内,return什么都没有 () - 这就是错误的含义。

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

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

然后,将您的 return 语句替换为

completion(comments:commentsList)

问题在于此函数的类型签名:

func loadComments(id:Int) -> [CommentsList]

你什么都不return。你调用这个函数:

service.apiCallToGet( ... )

但是,Swift 不会 return 任何隐含的东西,因此在您的错误中出现 ()(这意味着 void)。给出错误的那一行有点误导...