this is a small portion of the code:
@interface
BOOL isCarryingmallet;
@implementation
-(BOOL)isCarryingWeapon {
return isCarryingMallet;
}
-(int)getWeaponDamage {
if (isCarryingMallet)
return kVikingMalletDamage;
else
return kVikingFistDamage;
}
I don't understand how this works. Does return isCarryingmMallet;
return YES or NO? Why isn't there an == YES
in if (isCarryingMallet)
? Why is it if (isCarryingMallet)
not if (isCarryingWeapon)
.
Thanks for answering my newb questions!
The isCarryingWeapon
method returns the value of the isCarryingMallet
variable. If there were other possible weapons, that method could return a more complicated value, like (isCarryingMallet || isCarryingPlasmaCannon)
. Basically right now the only weapon that matters to this class is the mallet. When the isCarryingWeapon
method is called, this class says to itself, "Am I carrying a mallet?" If so, it knows it's carrying a weapon, so it returns true - "Yes, I've got a weapon." Otherwise it returns false.
As for the if
question - all if
statements do is determine whether the value in the parentheses evaluates to true or false. Equality statements are pretty common in if statements but they're not at all required. More specifically, anything that is not 0, null, or nil is true. So the following will all execute the code in the curly braces:
if (1) {...}
if (37) {...}
if (YES) {...}
if (true) {...}
Boolean variables are often named with the prefix is
so that this makes natural grammatical sense. In your case, you can parse
if (isCarryingMallet) {...}
as
If this guy is carrying a mallet, then...
method isCarryingWeapon
returns the value of isCarryingSword
boolean.
In getWeaponDamage
method you don't need to do an explicit comparison such as isCarryingMallet == TRUE
because the if statement will check directly the value of isCarryingMallet
and that value will be used as the result of a comparison. In other words, if it is TRUE the if statement will behave the same as if it made a comparison between two values and that comparison returned TRUE.
Why isn't there an "== YES" in "if (isCarryingMallet)"?
By default, statements inside if gets executed only if the condition is true. So,
if (isCarryingMallet) { /* ... */ }
Depending on the value of isCarryingMallet
, the statements are executed. Think like this -
if ( true ) { /* ... */ } // if isCarryingMallet value is true
Does "return isCarryingMallet;" return YES or NO?
Do you mean which value is returned? We don't know. The value is not set in your code snippet.
Your code snippet assumes that somewhere else we will find some code setting that variable to YES or NO (actually numbers, not text or a true Boolean, as C and Objective-C lack a true Boolean).