Ternary operator for setting a value based on the value of a variable

I thought I figured out how this would work, but maybe I am missing something small. I want to set the label text based on the value of another variable.

This is what I wrote, but it always returns null and throws a warning in the complier:

myLabel.text = [NSString stringWithFormat:@"%@", [[_singleDictionary objectForKey:_key]  isEqual: @"1" ? @"Single" : @"Three"]];

      

The compiler issues a warning:

Format specifies type 'id' but the argument has type 'BOOL' (aka 'bool')

      

I do not know why. I researched ternary operators for this, and when I build my code, I still get a warning. Basically I want to make the following if statement a ternary statement:

if ([[_singleDictionary objectForKey:_key] == @"1"])
{
     myLabel.text = @"Single";
}
else if ([[_singleDictionary objectForKey:_key] == @"3"])
{
     myLabel.text = @"Three";
}

      

+3


source to share


2 answers


As you wrote it, it tries to evaluate @ "1" to determine what to pass isEqual. I think if you use the result of isEqual as a comparison instead, it will do what you want. Like this:



myLabel.text = [[_singleDictionary objectForKey:_key] isEqual: @"1"] ? @"Single" : @"Three";

      

+2


source


You have parentheses in the wrong place, so the argument stringWithFormat

is the result:

[[_singleDictionary objectForKey:@"key"] isEqual:(@"1" ? @"Single" : @"Three")]

      

In other words, the triple is evaluated as an argument isEqual

, and the whole thing has a type BOOL

. I think you meant to do this, instead of this:



[[_singleDictionary objectForKey:_key] isEqual: @"1"] ? @"Single" : @"Three";

      

You might want to break it up so that it's not all on one line. It will probably be easier to read this path.

The key to solving such problems in the future is to understand what the error means. It tried to tell you that the format specifier in stringWithFormat

( %@

) was expecting id

, but got it instead BOOL

. This should have been your first indication that the second argument was not returning a string as you thought it was, but was evaluating a boolean value somehow. From there, you could more easily notice the parenthesis error.

+3


source







All Articles