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++;
Related
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("+")
}
I'm very confused even after looking through similar questions of what the(!) operator does when it is prefixed on a variable or other object in if statements, functions, etc?
Example:
mutating func add(value: T)
{
if !contains(items, value)
{
items.append(value)
}
}
the exclamation mark ! is used for two purposes. When you see it appear at the beginning of an object, such as in !contains(items, values), it means "NOT". For example...
let x = 10
let y = 5
if x == y {
print("x is equal to y")
} else if x != y {
print("x is NOT equal to y")
}
The above code will print => "x is NOT equal to y" .
The logical NOT (!) operator can be used to reverse boolean values. For example...
var falseBoolValue = false
falseBoolValue = !falseBoolValue
print(falseBoolValue)
The above code will print => "true"
In addition to the usage as the logical NOT operator, the exclamation mark is also used to implicitly unwrap optional values. Whenever you see the exclamation mark appear at the end of an object name, such as in someVariable!, it is being used to implicitly unwrap an optional value. Read about optionals to gain a better understanding of how ! is used with optional values.
it is NOT prefix there. Meaning your if looks for "items NOT containing value".
I am still totally new to julia and very irritated by the following behaviour:
immutable X
x::ASCIIString
end
"Foo" == "Foo"
true
X("Foo") == X("Foo")
false
but with Int instead of ASCIIString
immutable Y
y::Int
end
3 == 3
true
Y(3) == Y(3)
true
I had expected X("Foo") == X("Foo") to be true. Can anyone clarify why it is not?
Thank you.
Julia have two types of equality comparison:
If you want to check that x and y are identical, in the sense that no program could distinguish them. Then the right choice is to use is(x,y) function, and the equivalent operator to do this type of comparison is === operator. The tricky part is that two mutable objects is equal if their memory addresses are identical, but when you compare two immutable objects is returns true if contents are the same at the bit level.
2 === 2 #=> true, because numbers are immutable
"Foo" === "Foo" #=> false
== operator or it's equivalent isequal(x,y) function that is called generic comparison and returns true if, firstly suitable method for this type of argument exists, and secondly that method returns true. so what if that method isn't listed? then == call === operator.
Now for the above case, you have an immutable type that do not have == operator, so you really call === operator, and it checks if two objects are identical in contents at bit level, and they are not because they refer to different string objects and "Foo" !== "Foo"
Check source Base.operators.jl.
Read documentation
EDIT:
as #Andrew mentioned, refer to Julia documentation, Strings are of immutable data types, so why "test"!=="true" #=> true? If you look down into structure of a String data type e.g by xdump("test") #=> ASCIIString data: Array(UInt8,(4,)) UInt8[0x74,0x65,0x73,0x74], you find that Strings are of composite data types with an important data field. Julia Strings are mainly a sequence of bytes that stores in data field of String type. and isimmutable("test".data) #=> false
I met with this code, and I could not figure out what does this two question marks mean?
the Definition of this variable looks like following:
var featureImageSizeOptional: CGSize?
The code that makes me confused is:
let featureImageSize = featureImageSizeOptional ?? CGSizeZero
It's the coalescing operator. It returns the first expression (featureImageSizeOptional) if it's non-nil. If the first expression is nil, the operator returns the second expression (CGSizeZero).
See the Language Guide for more info.
The operator does not 'return the first expression' - it returns the unwrapped value of the first expression (if it is not nil). From the Apple documentation (emphasis mine):
The nil coalescing operator (a ?? b) unwraps an optional a if it
contains a value, or returns a default value b if a is nil. The
expression a is always of an optional type. The expression b must
match the type that is stored inside a.
The nil coalescing operator is shorthand for the code below:
a != nil ? a! : b
The code above uses the ternary conditional operator and *forced
unwrapping (a!) to access the value wrapped inside a when a is not
nil*, and to return b otherwise. The nil coalescing operator provides a
more elegant way to encapsulate this conditional checking and
unwrapping in a concise and readable form.
In most OO languages, where variables may point to objects, they may also have a null value, which is highly convenient.
In Matlab, I have a function which parses a command, and then returns a cell array, or false (which is equal to zero — which is another common pattern) if it fails:
function re = parse(s)
...
if (invalid)
re = false;
return;
end
end
The problem is that when I check the result, it gives an error:
re = parse(s);
if (false == re)
Undefined function 'eq' for input arguments of type 'cell'.
I've written a function to check it without an error: strcmp('logical', class(re)) && false == re, but that seems to be really slow for use in hot areas of the code, and also inconvenient if I have to add this function to every M file I'm writing.
Using NaN is even worse, because besides throwing that error, it also isn't equal to itself.
What's a better alternative for use with this pattern?
You can use the isequal function to compare any two items without causing that error. For example:
if isequal (re, false)
%code here
end
A good alternative is to use the empty array: [] and isempty(re) to check. This doesn't throw the error.
Reference: http://www.mathworks.com.au/matlabcentral/newsreader/view_thread/148764
If you can change the function parse one solution would be to return two output arguments [re status] = parse(s), where status would be logical variable. Set it to true in case of success, and to false otherwise.
I would use the empty cell array {} if it is not a valid result otherwise. Using empty matrices is MATLAB standard (see Evgeni Sergeev's answer), but using an empty cell array instead of an empty numeric array ensures that you'll always end up with the same type of result.
If, on the other hand, the empty cell array {} is a valid result of your function, then I'd use an exception to signalize a problem:
if invalid
error('Parse:InvalidArgumentError', 'The input is invalid.');
end
Make sure to use an appropriate error ID (first argument to error) so that you can catch exactly that exception when you call the function:
try:
result = parse(something);
catch ME
if strcmp(ME.identifier, 'Parse:InvalidArgumentError')
fprintf('Ooops\n');
else
% Some other error
ME.rethrow();
end
end
I think the problem is that matlab functions don't return pointers but copies of values.
IMHO the best best approach would be to define your own "pointer" class. Inside you can define an "isNull()" command or even override comparison to produce the behavior you desire.