Reputation: 17169
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...
Upvotes: 1
Views: 139
Reputation: 31645
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.
Upvotes: 2
Reputation: 304
All you need to do is add a space
self.collectionView?.insertItems(at: [IndexPath.init(row: (self.flights.count - 1), section: 0)])
Upvotes: 0