我无法快速从函数返回自定义对象数组。我总是收到[(custon object)] is not convertable to '()'错误消息。我认为我违反了某些快速协议。下面是我的代码。请让我知道我违反了哪个。
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 '()'"
})
}
}
Run Code Online (Sandbox Code Playgroud)
您的return语句位于Web服务的完成块内,该块不返回任何内容()-这就是错误的含义。
围绕异步Web调用包装的方法无法返回值,因为您必须阻塞直到Web调用完成。您的loadComments方法应采用一个完成块参数,该参数应[CommentsList]作为参数:
func loadComments(id: Int, completion:(comments:[CommentsList])->Void) {
// existing code
Run Code Online (Sandbox Code Playgroud)
然后,将您的return语句替换为
completion(comments:commentsList)
Run Code Online (Sandbox Code Playgroud)