简体   繁体   中英

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

I can't able to return a custom array of objects from a function in swift. I am always getting [(custon object)] is not convertable to '()' error message. I think i'm violating some swift protocol. Below is my code. Please let me know which i'm violating.

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

Your return statement is inside the completion block of your web service, which returns nothing () - that's what the error means.

Methods that are wrappers around asynchronous web calls can't return values, because you'd have to block until the web call had finished. Your loadComments method should take a completion block parameter, which takes [CommentsList] as an argument:

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

Then, replace your return statement with

completion(comments:commentsList)

The issue is with the type signature of this function:

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

You don't return anything. You call this function:

service.apiCallToGet( ... )

But, Swift does not return anything implicitly hence the () (which means void ) in your error. The line the error is given is slightly misleading...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM