4

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

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.