2

I can not understand what I did wrong


I have an app which loads posts and its comments. The view controller requests a function from an another file, which returns back (response?, comments?)

I get one error:

Initializer for conditional binding must have Optional type, not '(ActionResult?, [PostComment]?)'

For the line

if let (response, comments) = (response, comments )

What did I wrong?

commentsViewController

postComments.loadCommentForPost(id: postId) { (response, comments) in
            // ERROR here: Initializer for conditional binding must have Optional type, not '(ActionResult?, [WorldMessageComment]?)'
            if let (response, comments) = (response, comments ) {
                if response!.success == 1 {
                    DispatchQueue.main.async(execute: {() -> Void in
                            self.comments = comments!
                            self.tableView.reloadData()
                        })
                } else {
                    DispatchQueue.main.async(execute: {() -> Void in
                        self.handleResponses.displayError(title: response!.title, message: response!.message)
                    })
                }
            }
        }

commentFunctions

func loadCommentsForPost(id: Int, completion: @escaping ((ActionResult?), [PostComment]?)->()){

        // downloading the data and then

        let comments : [PostComment] = ...

        // Succesful
        return completion((ActionResult(success: 1, title: responseTitle, message: responseMessage)), comments)

    }
2
  • Related: Swift optional binding with tuples. Commented Apr 22, 2018 at 20:37
  • Unrelated, in loadCommentsForPost, that return statement doesn't make sense. You can remove the return keyword and just call completion. Also, in the closure where you call loadComments, what do you want to do if either response or comments was nil? Do nothing? Commented Apr 23, 2018 at 0:24

1 Answer 1

4

The issue is in the line:

if let (response, comments) = (response, comments ) {

What you are basically doing is creating a new non optional tuple on the right hand side of the assignment (with two optional components), so the compilator complains that you can't use if let with a non optional type.

You can in fact consider that the tuple return by loadCommentsForPost is already "split" in the arguments of the callback, so you can handle response and comments separately.

postComments.loadCommentForPost(id: postId) { response, comments in
    if let response = response, let comments = comments {
       if response.success == 1 {
       ...
Sign up to request clarification or add additional context in comments.

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.