I am importing price information and adding + or -.
I put the title code in print () and it works but I do not know what it means.
print("\(IntValue ?? 0 == -1 ? "-" : "+")")
Please explain it briefly to me.
Kevin's answer is very good.
Some background that helps explain further:
The code you posted uses two rather cryptic operators together.
?? is the nil-coalescing operator.
It takes an optional value, which can contain nil, and provides a new value to use when it does contain nil.
Edit:
(Note that you can skip the nil-coalescing operator and use IntValue == -1 instead. That works because only a non-nil value of -1 is equal to -1. An optional that contains nil is not equal to -1.
You could rewrite the line as
print("\(IntValue == -1 ? "-" : "+")")
And get the same result.)
The next tricky bit is the "ternary operator". This comes from C. It's quite cryptic, but also quite useful.
It takes the form boolean ? value_for_true : value_for_false
Where boolean is a boolean expression that evaluates to true or false.
If boolean is true, then the result of the whole ternary expression is the value_for_true sub-expression.
If boolean is false the result of the whole ternary expression is the value_for_false sub-expression.
IntValue ?? 0 == -1 is the boolean part of your ternary expression. It evaluates as true if IntValue is -1. It evaluates as false if IntValue contains any other value, or if it contains nil.
(Note that variables and let constants should start with lower-case letters, so IntValue should be intValue.)
The variable IntValue is an optional, which means its either an Integer or nil. IntValue ?? 0 means that if IntValue exists, then use the value of IntValue. If IntValue is nil, then use the value 0. Next, compare that value with -1. If that value is equal to -1, then print -. If that value does not equal -1, then print +.
Here's equivalent code with only if statements:
var defaultInt = 0
if IntValue != nil {
defaultInt = IntValue! // force unwrap the optional value
}
if defaultInt == -1 {
print("-")
}
else {
print("+")
}
Related
Dart suggest me to use if null operator . Why ? and how to use it?
This is my code:
var name;
name != null ? name : 'nobody';
In other languages we can use the logical-or shortcut. If maybeSomeNumber() returns null, assign a default value of 2:
value = maybeSomeNumber() || 2
In Dart we can't do this because the expression needs to be a boolean (“the operands of the || operator must be assignable to bool”).
That's why the ?? operator exists:
var value = maybeSomeNumber() ?? 2;
Similarly, if we wanted to ensure a value argument was not-null we'd do:
value = value ?? 2;
But there's an even simpler way.
Fallback assignment operator: ??=
value ??= 2;
check the original artical: https://flutterigniter.com/checking-null-aware-operators-dart/
I don't think we need to use conditions or ternary operator here. It will increase program complexity. Try below
name = name || 'nobody';
I have two textboxes. When the user clicks on a button, I need to check if the values entered into the textfields are positive integers.
I try to do this using the following statement:
if ((Int(txta.stringValue))! < 0 ||(Int(txtb.stringValue))! < 0)
{
// Display error message
}
But it seems there is an issue with the if statement syntax.
Expected ',' separator is the error produced.
What I'm I doing wrong?
Please advise.
There are two problems:
Binary operators (such as ||) must have whitespace on both sides
(or on none), that's what causes the syntax error. (See what are the rules for spaces in swift.)
if (Int(txta.stringValue))! < 0 cannot be used to check for integer
input because the forced unwrap crashes at runtime if the string is
not an integer.
Int(txta.stringValue) returns nil if the string is not an integer, so
a possible check for integer input would be
if Int(txta.stringValue) == nil || Int(txtb.stringValue) == nil {
// display error message
}
But most probably you need the integer values themselves (in the case of valid input),
that's what optional binding is for
(see also When should I compare an optional value to nil?):
if let a = Int(txta.stringValue), let b = Int(txtb.stringValue) {
// Valid input, values are in `a` and `b` ...
} else {
// display error message
}
Additional conditions can be added to check the valid range, e.g.
if let a = Int(txta.stringValue), let b = Int(txtb.stringValue), a > 0, b > 0 {
// Valid positive input, values are in `a` and `b` ...
} else {
// display error message
}
Or with guard:
guard let a = Int(txta.stringValue), let b = Int(txtb.stringValue), a > 0, b > 0 else {
// display error message
return
}
// Valid positive input, values are in `a` and `b` ...
This is an ideal case for Optional.map and Optional.flatMap:
if (Int(textA.stringValue).map{ 0 <= $0 } ?? false) &&
(Int(textB.stringValue).map{ 0 <= $0 } ?? false) {
}
To break it down:
textA is a NSTextField.
textA.stringValue is some non-optional String value
Int(textA.stringValue) converts the text field's non-optional string value into an Int? value (a.k.a. Optional<Int>). It's optional, since the conversion from String to Int can fail (when the string doesn't encode an integer)
map{ 0 <= $0 } is called on that Int?. This is Optional.map, not to be confused with more common map functions, like Array.map. If the optional has some value, then the provided closure is applied to it. Otherwise, the nil is propagated onwards. Thus, the result of Int(textA.stringValue).map{ 0 <= $0 } is Bool?, with three possible values:
true (Optional.some(true)), meaning the text field encodes a positive (non-negative) integer.
false (Optional.some(false)), meaning the text field encodes a negative integer.
nil (Optional.none), meaning the text field doesn't encode an integer at all.
The nil coalescing operator is used (??), to merge the nil case into the false case. Thus, the result of Int(textA.stringValue).map{ 0 <= $0 } ?? false has 2 values:
true meaning the text field encodes a positive integer.
false meaning the text field encodes a negative integer, or doesn't encode a number at all. In either case, it doesn't encode a positive integer
The process is repeated for textB, and the two expressions are anded together (&&)
I have to convert strings usually containing an integer number into values of type Bool. The rule would be to get true or any non-zero value. But invalid numbers shall lead to false.
If the strings were always valid numbers, the code would be like this:
let stringValue = "1"
let boolValue = Int(stringValue) != 0
However, that doesn't work if stringValue is empty, because then the Int() function returns nil, and that is unequal to 0, thus the result ends up being true when I want false.
What's an elegant way to solve this in Swift 3? I like to avoid extra lines with if clauses.
Note: If the string could only contain "1" for true values, testing for == 1 would be the answer. But I like to allow other non-zero values for true as well. In other words, I like to have any valid number other than 0 become true.
For that you can use Nil-Coalescing Operator.
let boolValue = (Int(stringValue) ?? 0) != 0
This Perl code is part of the variable declaration at the beginning of a piece of code. What does it mean?
my $EXPLICIT_YEAR = $ALL_PAGES ? 0 : ($store{year} || $current_year);
It's equivalent to this:
my $EXPLICIT_YEAR;
if ($ALL_PAGES) {
$EXPLICIT_YEAR = 0;
}
else {
# $EXPLICIT_YEAR = $store{year} || $current_year;
if ($store{year}) {
$EXPLICIT_YEAR = $store{year};
}
else {
$EXPLICIT_YEAR = $current_year;
}
}
The $conditional ? $true : $false portion is a ternary if.
The $store{year} || $current_year portion uses the fact that the || operator returns the first value that evaluates to true, allowing $current_year to be used if $store{year} is "false" (zero, empty string, etc.)
my $EXPLICIT_YEAR = $ALL_PAGES ? 0 : ($store{year} || $current_year);
This expression is using the Ternary "?:" operator, combined with a subexpression using the || C-style logical OR. See perldoc perlop.
$ALL_PAGES ?
The expression before the ? - the condition - is evaluated as a boolean expression. A true value meaning any value that is not zero, the empty string or undefined (not declared).
0 : ( $store{year} || $current_year )
The values on either side of : are the values to be returned, depending on the return value of the condition. If the condition evaluates true, return the leftmost value, otherwise the rightmost. The leftmost value is simply zero 0.
$store{year} || $current_year
The rightmost value is an expression itself, using the C-style logical OR operator. It will return the leftmost value, if it evaluates true (and ignore the rightmost). Otherwise it will return the rightmost value. So:
if $ALL_PAGES is true, then set $EXPLICIT_YEAR to zero
else if $ALL_PAGES is false, then:
if $store{year} is true, then set $EXPLICIT_YEAR to $store{year}
else set $EXPLICIT_YEAR to $current_year
I'm not a Perl developer, but I'm 99% sure (this holds in most other languages) that it equates to this: If the variable $ALL_PAGES is true (or 1), then 0 is evaluated, and if not, ($store{year} || $current_year) is evaluated.
i think thats a way of doing a if/then/else
see here: http://www.tutorialspoint.com/perl/perl_conditions.htm
I know 0 perl but a lot of C, so taking a guess here:
Set variable EXPLICIT_YEAR to
( if ALL_PAGES == true then 0
else ( (get store indexed at year) or current_year ))
The or operation is
false or false = false
false or true = true
true or false = true
true or true = true
In objective-c is the end result of !variable the same as variable==nil Also I think I read somewhere that iVars are initialized to "nil" (i.e. o) but sadly I can't seem to find where I spotted it now. If I am correct is this initialization to nil part of declaring an iVar or is it linked to something else like #property?
i.e. do these evaluate the same ...
if(!myObject) ...
and
if(myObject == nil) ...
Cheers Gary.
Edited: hopefully for more clarity.
Your question subject and question body appear to be asking different things, so…
To answer the question subject: No, ! and nil are not at all the same. ! is an operator that returns the logical negation of its operand (that is, !0 returns 1 and ! with anything else returns 0), while nil is a macro for 0.
To answer the question itself: Yes, !foo and foo == nil give the same result for object variables. And yes, instance variables are initialized to 0. So are static variables and global variables.
! is a C logical operator that means not (like && means and and || means or).
nil is the way for expressing an unitialized object pointer.
Applied to a pointer, the value of the expression is TRUE whenever the pointer is NULL or nil.
In the end, if(!myObject) and if(myObject==nil) have the same behaviour.
In objective-c the ! is a boolean operator and returns the opposite of a boolean value or expression result. In the below example myObj is really evaluating it's pointer value as a boolean, zero or non-zero. Since myObj is a non-zero pointer this evaluates to true. !myObj will return the opposite, in this case it would return false.
id myObj = nil;
int x = 0;
if (myObj)
x++;