1

I am just starting out with Swift, coming from Objective-C. I have this line:

self.collectionView?.insertItems(at: [IndexPath.init(row: (self.flights.count -1), section: 0)])

I get an error saying: Expected ',' separator after 'count'.

Why on earth can I not do a simple sum, the count -1? A little quirk of Swift I haven't yet learnt, or its too early in the morning...

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Josh Kahane
  • 16,765
  • 45
  • 140
  • 253
  • 1
    When you put `-` before `1` without space Swift interprets `-` as prefix unary operator. And you got something like `self.flights.count (-1)`, which is not grammatically correct` – user28434'mstep Dec 05 '16 at 09:43
  • 2
    See [what are the rules for spaces in swift](http://stackoverflow.com/questions/31301715/what-are-the-rules-for-spaces-in-swift). – Martin R Dec 05 '16 at 09:47
  • 1
    I think you meant "Simple Int subtraction error"... :) – Ahmad F Dec 05 '16 at 11:06

2 Answers2

2

Referring to Apple's "Lexical Structure" Documentation:

The whitespace around an operator is used to determine whether an operator is used as a prefix operator, a postfix operator, or a binary operator. This behavior is summarized in the following rules:

  • If an operator has whitespace around both sides or around neither side, it is treated as a binary operator. As an example, the +++ operator in a+++b and a +++ b is treated as a binary operator.

  • If an operator has whitespace on the left side only, it is treated as a prefix unary operator. As an example, the +++ operator in a +++b is treated as a prefix unary operator.

  • If an operator has whitespace on the right side only, it is treated as a postfix unary operator. As an example, the +++ operator in a+++ b is treated as a postfix unary operator.

  • If an operator has no whitespace on the left but is followed immediately by a dot (.), it is treated as a postfix unary operator. As an example, the +++ operator in a+++.b is treated as a postfix unary operator (a+++ .b rather than a +++ .b).

Note: ++ and -- has been removed from Swift 3. For more information, check 0004 Swift evolution proposal.

Means that the minus operator in self.flights.count -1 treated as prefix unary operator (second rule).

To make it more clear, the compiler reads self.flights.count -1 as: self.flights.count, next to it there is a minus one, but NOT a subtraction operation. By applying the second rule, the minus is a prefix unary operator for the 1.

Obviously, you want the compiler to treat the minus operator as a binary operator, so what you should do is to add whitespace around both sides of the minus (applying the first rule):

self.collectionView.insertItems(at: [IndexPath.init(row: (flights.count - 1), section: 0)])

Hope this helped.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
0

All you need to do is add a space

self.collectionView?.insertItems(at: [IndexPath.init(row: (self.flights.count - 1), section: 0)])
Peter
  • 296
  • 4
  • 11