0

How can I show array count minus array count? I have two arrays like this:

var likedBy = [NSArray]()
var dislikedBy = [NSArray]()

And I am trying to get the count as a string on UITextLabel like this:

imageCell.likeLabel.text = self.likedBy.count - self.dislikedBy.count

But I get error:

No "-" candidates produce the expected contextual result type "String?"

Any suggestions?

3
  • String(self.likedBy.count - self.dislikedBy.count) Commented Apr 12, 2016 at 8:35
  • hint: count is a number the text is a string. Commented Apr 12, 2016 at 8:37
  • 1
    Suggestion #1: Read the error message. – Suggestion #2: If you get compiler errors that you don't understand, split the expression into multiple statements: let diff = self.likedBy.count - self.dislikedBy.count; imageCell.likeLabel.text = diff. You should see the problem now! Commented Apr 12, 2016 at 8:40

3 Answers 3

3

You should use string interpolation with \() because count property returns Int and you need a String to set the text property:

imageCell.likeLabel.text = "\(self.likedBy.count - self.dislikedBy.count)"
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Quick question - In the cellForItemAtIndexPath - what is difference between indexPath.row and indexPath.item?
item: An index number identifying an item in a section of a collection view.
Browse through stackoverflow.com/a/14765781/2035845 for more info on indexpath.item vs indexpath.row!!
2

replace your line

imageCell.likeLabel.text = "\(self.likedBy.count - self.dislikedBy.count)"

Comments

1

You might also want to write an extension on NSArray to provide a element count difference so your code is cleaner and the responsibilities lie in the right place. As in, your main code flow is not interested in working out the difference between two array counts, it wants to know how many likes there are left, after the dislikes have been subtracted.

extension NSArray {
    func elementCountDiff(array: NSArray) -> Int {
        return self.count - array.count
    }
}

...

imageCell.likeLabel.text = String(self.likedBy.elementCountDiff(self.dislikedBy))

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.