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?

Roduck Nickes
  • 1,021
  • 2
  • 15
  • 41
  • String(self.likedBy.count - self.dislikedBy.count) – ogres Apr 12 '16 at 08:35
  • hint: count is a _number_ the text is a _string_. – holex Apr 12 '16 at 08: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! – Martin R Apr 12 '16 at 08:40

3 Answers3

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)"
Said Sikira
  • 4,482
  • 29
  • 42
2

replace your line

imageCell.likeLabel.text = "\(self.likedBy.count - self.dislikedBy.count)"
itsji10dra
  • 4,603
  • 3
  • 39
  • 59
Ankit Kushwah
  • 539
  • 4
  • 16
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))
Michael
  • 1,213
  • 6
  • 9