Simple Int sum error - swift

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...

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.

All you need to do is add a space
self.collectionView?.insertItems(at: [IndexPath.init(row: (self.flights.count - 1), section: 0)])

Related

Regular expression with condition on inner expressions

I would like to build a regular expression for replacing a sentence with "per" when it should be (a readable version of a sentence with quantities).
That is:
"3/unit" must match
"unit/3" must match
"feet/second" must match
"05/07" must not match
I know how to create something like "\D+/\D+".
But how can I build a regex saying "not both right and left expressions match \D+" ?
You can use
^(?![0-9]+/[0-9]+$)[^/]+/[^/]+$
See the regex demo. Details:
^ - start of string
(?![0-9]+/[0-9]+$) - a negative lookahead that fails the match if there are one or more digits, /, one or more digits and end of string position immediately to the right of the current location
[^/]+/[^/]+ - one or more chars other than /, a / char, and then one or more chars other than /
$ - end of string.

Why are leading-hyphen options permitted on `use` lines without fat comma and with strict?

Why is the following use line legal Perl syntax? (Adapted from the POD for parent; tested on Perl 5.26.2 x64 on Cygwin.)
package MyHash;
use strict;
use Tie::Hash;
use parent -norequire, "Tie::StdHash";
# ^^^^^^^^^^ A bareword with nothing to protect it!
Under -MO=Deparse, the use line becomes
use parent ('-norequire', 'Tie::StdHash');
but I can't tell from the use docs where the quoting on -norequire comes from.
If use strict were not in force, I would understand it. The bareword norequire would become the string "norequire", the unary minus would turn that string into "-bareword", and the resulting string would go into the use import list. For example:
package MyHash;
use Tie::Hash;
use parent -norequire, "Tie::StdHash";
Similarly, if there were a fat comma, I would understand it. -foo => bar becomes "-foo", bar because => turns foo into "foo", and then the unary minus works its magic again. For example:
package MyHash;
use strict;
use Tie::Hash;
use parent -norequire => "Tie::StdHash";
Both of those examples produce the same deparse for the use line. However, both have quoting that the original example does not. What am I missing that makes the original example (with strict, without =>) legal? Thanks!
You already cited perldoc perlop, but it is relevant here.
Unary - performs arithmetic negation if the operand is numeric, including any string that looks like a number. If the operand is an identifier, a string consisting of a minus sign concatenated with the identifier is returned. ... One effect of these rules is that -bareword is equivalent to the string "-bareword".
This behavior of the unary minus operator is applied to the bareword before the strict checks are applied. Therefore, unary minus is a kind of quoting operator that also works in strict mode.
Similarly, barewords as the invocant in method invocation do not need to be quoted as long as they are not a function call:
Foo->bar; # 'Foo'->bar(); --- but only if no sub Foo exists
print->bar; # print($_)->bar();
However, the unary minus behaviour seems to be due to constant folding, not due to a special case in the parser. For example, this code
use strict;
0 ? foo : bar;
will only complain about the bareword "bar" being disallowed, suggesting that the bareword check happens very late during parsing and compilation. In the unary minus case, the bareword will already have been constant-folded into a proper string value at that point, and no bareword remains visible.
While this is arguably buggy, it is also impossible to change without breaking backwards compatibility – and this behaviour is used by many modules such as use parent to communicate options. Compare also similar idioms on command line interfaces, where options usually begin with a dash.
From perlop
Symbolic Unary Operators
Unary "-" performs arithmetic negation if the operand is numeric, including any
string that looks like a number. If the operand is an identifier, a string
consisting of a minus sign concatenated with the identifier is returned.
Otherwise, if the string starts with a plus or minus, a string starting with
the opposite sign is returned. One effect of these rules is that -bareword is
equivalent to the string "-bareword". If, however, the string begins with a
non-alphabetic character (excluding "+" or "-"), Perl will attempt to convert
the string to a numeric and the arithmetic negation is performed. If the string
cannot be cleanly converted to a numeric, Perl will give the warning Argument
"the string" isn't numeric in negation (-) at ....
So because of the rules of Perl parsing -name is treated as "-name" even under use strict

Is this response from the compiler valid?

The following code invokes an error. I could not find any information on this is in the reference. The lack of whitespace on the right hand side of the '=' operator is an error.
let names =["Anna", "Alex", "Brian", "Jack"]
Any other combination of this syntax compiles. Anyone know if this is truly invalid syntax per what we know of Swift right now?
EDIT: Error response is: Prefix/postfix '=' is reserved
ANSWER: This excerpt seems to answer my question. I just couldn't find it for the longest time:
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).
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l
Add a space after the =. (=[ looks too sad to be an operator.) It's probably seeing =value as a use of a (possible, but not implemented) prefix operator.
Swift isn't entirely whitespace-agnostic like C... in particular, it uses whitespace to distinguish prefix from postfix operators (because ++i++ in C is a grammar oddity). But it's not ridiculously strict about whitespace like Python either.
Try adding a space between the = and [.
When the equals sign is directly in front of the bracket, the compiler assumes that you are trying to perfom a prefix operation on the array.
Place a space between = and [,
let names = ["Anna", "Alex", "Brian", "Jack"]
It seems that =[ is a reserved operator.

PCRE: Difference between .* and .*? in regular expressions

I was wondering, why .* and .*? is not the same in PCRE regular expressions (for example in PHP's preg_match(). Dot . is symbol for any possible character and * is symbol for 0 to infinity repetition. Why is there symbol ? which means 0 to 1 repetition? However it is not obviously the same, because .*? is not interchangeable with .*, but I can't see logic difference, I have to always try what works and what does not work in certain case. I suppose that .* should match nothing to anything and ? is redundant, because it specify that .* can be 0 or 1 times - but zero times is empty string and empty string should be matched by .* too.
Can anyone explain me what is the exact difference and show me short example?
Thanks
i love wantons because they are tasty snacks
In the above string, let's say you try to match it with i.*s. The result would be the entire string, because this is called a greedy match. It matches from the first instance of i until the last instance of s.
If you were to use the non-greedy modifier ?, like i.*?s, then you would result in the following:
i love wantons
This is because the non-greedy ? modifier only matches until the first instance of s.
* is a greedy match - in other words, match zero to many times, as many times as possible. *? is a minimal match - in other words, match zero to many times, as few times as possible for the rest of the pattern to make sense. Similarly, +? is a minimally-matching version of +.
Consider the string this is "quoted" and this is "also quoted". The regular expression ".*" would match one result, "quoted" and this is "also quoted"; ".*?" would match twice, "quoted" and "also quoted".

flip-flop-operator/readline-counter question

Reading this Perl: extract rows from 1 to n (Windows) I didn't understand the flip-flop-operator/readline-counter part.
perl -nE 'say $c if $c=1..3' my_file
1
2
3E0
Could someone explain me more detailed where this output comes from?
To quote perlop:
In scalar context, ".." returns a
boolean value. The operator is
bistable, like a flip-flop, and
emulates the line-range (comma)
operator of sed, awk, and various
editors. Each ".." operator maintains
its own boolean state, even across
calls to a subroutine that contains
it. It is false as long as its left
operand is false. Once the left
operand is true, the range operator
stays true until the right operand is
true, AFTER which the range operator
becomes false again. It doesn't become
false till the next time the range
operator is evaluated. It can test the
right operand and become false on the
same evaluation it became true (as in
awk), but it still returns true once.
If you don't want it to test the right
operand until the next evaluation, as
in sed, just use three dots ("...")
instead of two. In all other regards,
"..." behaves just like ".." does.
The right operand is not evaluated
while the operator is in the "false"
state, and the left operand is not
evaluated while the operator is in the
"true" state. The precedence is a
little lower than || and &&. The value
returned is either the empty string
for false, or a sequence number
(beginning with 1) for true. The
sequence number is reset for each
range encountered. The final sequence
number in a range has the string "E0"
appended to it, which doesn't affect
its numeric value, but gives you
something to search for if you want to
exclude the endpoint. You can exclude
the beginning point by waiting for the
sequence number to be greater than 1.
If either operand of scalar ".." is a
constant expression, that operand is
considered true if it is equal (==)
to the current input line number (the
$. variable).
(emphasis added)