I have a question about Objective C
I want an inverted if statement. Like: if (!example.hidden == YES) {
Here's my code:
if ((randomBallTouch.x>_randomColorBall.center.x-(_randomColorBall.frame.size.width)/2) &&
(randomBallTouch.x<_randomColorBall.center.x+(_randomColorBall.frame.size.width)/2) &&
(randomBallTouch.y>_randomColorBall.center.y-(_randomColorBall.frame.size.height)/2) &&
(randomBallTouch.y<_randomColorBall.center.y+(_randomColorBall.frame.size.height)/2)) {
_randomColorBall.center = CGPointMake(randomBallTouch.x, randomBallTouch.y);
if (_randomColorBall.hidden == NO) {
_redBall.center = CGPointMake(_redBall.center.x, _redBall.center.y - 200);
}
}
But when i do: if(!(randomBallTouch.x>_randomColorBall.center.x)) etc. It does not work.
And I can't do else because that will bug with the other two if statements.
Any help?? I am using Xcode 5.1.
You can't just add an ! at the beginning to invert the condition. You need to wrap the whole expression in a set of parentheses first.
If you have:
if (a && b) {
then the inversion is:
if (!(a && b)) {
You didn't add those parentheses.
Try this, just replace your if with this one.
if(!((randomBallTouch.x > (_randomColorBall.center.x-(_randomColorBall.frame.size.width)/2)) && (randomBallTouch.x < (_randomColorBall.center.x+(_randomColorBall.frame.size.width)/2)) && (randomBallTouch.y > (_randomColorBall.center.y-(_randomColorBall.frame.size.height)/2)) &&(randomBallTouch.y < (_randomColorBall.center.y+(_randomColorBall.frame.size.height)/2)))) {
You are missing a lot of parenthesis to make your statement a valid boolean.
Related
I have been trying to implement the shunting yard algorithm, but the output of my parser is incorrect.
let mut stack: Vec<String> = vec![];
let mut op_stack: Vec<String> = vec![];
for current in sub_tree {
if current.tok_type == TokenType::NUMBER || current.tok_type == TokenType::NEGNUMBER {
self.parse();
stack.push(current.content.clone());
}
if current.tok_type == TokenType::SUBBIN
|| current.tok_type == TokenType::PLUSBIN
|| current.tok_type == TokenType::DIVBIN
|| current.tok_type == TokenType::MULBIN
{
while op_stack.len() > 0 && op_stack.last().unwrap().to_string() != "(" {
if op_prec(&op_stack.last().unwrap().to_string()) > op_prec(¤t.content)
|| (op_prec(&op_stack.last().unwrap().to_string()) == op_prec(¤t.content)
&& op_asso(¤t.content) == "left")
{
stack.push(op_stack.pop().unwrap().to_string());
} else {
break;
}
}
op_stack.push(current.content.to_string())
}
}
The original equation I am parsing: 1 + 2 * 3
I expected the following output: 1 2 3 * +
Instead I get this: 1 2 3 + *
I think I am going wrong somewhere in my while loop but I don't really know. I tried to follow the example on the Wikipedia article.
I forgot I had to pop from the operator stack back into the output stack at the end.
Comparing your code
if current.tok_type == TokenType::SUBBIN
|| current.tok_type == TokenType::PLUSBIN
|| current.tok_type == TokenType::DIVBIN
|| current.tok_type == TokenType::MULBIN
{
while op_stack.len() > 0 && op_stack.last().unwrap().to_string() != "(" {
if op_prec(&op_stack.last().unwrap().to_string()) > op_prec(¤t.content)
|| (op_prec(&op_stack.last().unwrap().to_string()) == op_prec(¤t.content)
&& op_asso(¤t.content) == "left")
{
stack.push(op_stack.pop().unwrap().to_string());
} else {
break;
}
}
op_stack.push(current.content.to_string())
}
with the Wikipedia code https://en.wikipedia.org/wiki/Shunting-yard_algorithm
- an operator o1:
while (
there is an operator o2 other than the left parenthesis at the top
of the operator stack, and (o2 has greater precedence than o1
or they have the same precedence and o1 is left-associative)
):
pop o2 from the operator stack into the output queue
push o1 onto the operator stack
It looks like they are functionally identical.
So I suspect the problem is not with the code, but instead with the precedence table. If you have the precedence of + and * the wrong way round, then you would get this behaviour. It is easy to get this mixed up as some source have precedence going from tighter binding to loser one and some have the opposite. Compare Wikipedia order of operations and Operator Precedence in Java, use the former.
how to use ternary if else with two or more condition using "OR" and "AND" like
if(foo == 1 || foo == 2)
{
do something
}
{
else do something
}
i want to use it like
foo == 1 || foo == 2 ? doSomething : doSomething
If you're referring to else if statements in dart, then this ternary operator:
(foo==1)? something1():(foo==2)? something2(): something3();
is equivalent to this:
if(foo == 1){
something1();
}
elseif(foo == 2){
something2();
}
else something3();
For three conditions use:
value: (i == 1) ? 1 : (i == 2) ? 2 : 0
Try below
(2 > 3)?print("It is more than 3"):print("It is less than 3");
////Prints It is less than 3 to the console
For AND try this,
// here both or multiple conditions needs to satisfy
if (primaryImageUploaded == true && signatureImageUploaded == true) {
// status bool condition in true
} else {
// if false
}
For OR try this,
// here need ONLY any one condition to satisfy
if (primaryImageUploaded == true || signatureImageUploaded == true) {
// status bool condition in true
} else {
// if false
}
Another Dart Syntax
if (100 > 50) {
print("100 is greater than 50");
}
it is easy,
if(foo == 1 || foo == 2)
{
do something
}
{
else do something
}
it can be written thus for OR statement
foo==1 || foo==2 ? do something : else do something
it can be written thus for AND statement
foo==1 && foo==2 ? do something : else do something
both will work perfectly
EDITED
The original answer has run a little bit of from the question asked. Below is my edited answer.
To use ternary operator
(foo == 1 || foo == 2) ? doSomething() : doSomethingElse();
For my cleaner approach
{1, 2}.contains(foo) ? doSomething() : doSomethingElse();
ORIGINAL
The cleaner way for me is
if ({1, 2}.contains(foo)) {
//do something
} else {
//do something else
}
Here is an example of the same
Text((managerStatus == "pending")
? "Requested"
: (adminStatus == "confirm")
? "Amount credited"
: "Admin Pending")
Try this:
foo == 1 ? doSomething1 : (foo == 2 ? doSomething1 : doSomething2)
If you have to include multiple conditions then you should use parantheses
Simple Multiple check in one condition
if(in_array($foo, [1,2,'other'])) {
//do something
}
else {
//else do something
}
void main(){
var a,b,c,d;
a = 7;
b = 9;
c = 11;
d = 15;
print((a>b)?((a>c)?((a>d)?a:d):c):(b>c)?((b>d)?b:d):(c>d)?c:d);
}
I'm trying to filter an array in swift, it works great when I'm just trying to filter a few things but when I add to the list I get this error:
Expression was too complex to be solved in reasonable time; consider
breaking up the expression into distinct sub-expressions
Here is my code with the above error:
filteredArray = workArray.filter { $0.stateName.localizedCaseInsensitiveContainsString(searchString!) || $0.firstName.localizedCaseInsensitiveContainsString(searchString!) || $0.lastName.localizedCaseInsensitiveContainsString(searchString!) || $0.countyName.localizedCaseInsensitiveContainsString(searchString!) || $0.cityName.localizedCaseInsensitiveContainsString(searchString!) || $0.communityName.localizedCaseInsensitiveContainsString(searchString!) || $0.sectionName.localizedCaseInsensitiveContainsString(searchString!) || $0.notes.localizedCaseInsensitiveContainsString(searchString!) || $0.email1.localizedCaseInsensitiveContainsString(searchString!) || $0.email2.localizedCaseInsensitiveContainsString(searchString!) || $0.email3.localizedCaseInsensitiveContainsString(searchString!) || $0.title.localizedCaseInsensitiveContainsString(searchString!) || $0.jobsiteID.localizedCaseInsensitiveContainsString(searchString!)}
I have tried to split this process up like this
filteredArray = workArray.filter { $0.stateName.localizedCaseInsensitiveContainsString(searchString!) || $0.firstName.localizedCaseInsensitiveContainsString(searchString!) || $0.lastName.localizedCaseInsensitiveContainsString(searchString!) || $0.countyName.localizedCaseInsensitiveContainsString(searchString!) || $0.cityName.localizedCaseInsensitiveContainsString(searchString!) || $0.communityName.localizedCaseInsensitiveContainsString(searchString!) || $0.sectionName.localizedCaseInsensitiveContainsString(searchString!) || $0.notes.localizedCaseInsensitiveContainsString(searchString!) || $0.email1.localizedCaseInsensitiveContainsString(searchString!)}
and
filteredArray.appendContentsOf(workArray.filter { $0.email2.localizedCaseInsensitiveContainsString(searchString!) || $0.email3.localizedCaseInsensitiveContainsString(searchString!) || $0.title.localizedCaseInsensitiveContainsString(searchString!) || $0.jobsiteID.localizedCaseInsensitiveContainsString(searchString!)})
But I am getting duplicate objects in the array.
I could write something else that would then look for and delete duplicate objects but I would rather not. My question is how should I be filtering all this items.
Thank you for all the help
Factor that behemoth of an expression out to a method on your datatype.
extension MyDataThingy {
func anyFieldContains(searchTerm term: String) -> Bool {
let fieldValues = [self.stateName, self.firstName, /* etc. */]
for value in fieldValues {
if value.localizedCaseInsensitiveContainsString(term) {
return true
}
}
return false
}
}
Then:
filteredArray = workArray.filter { $0.anyFieldContains(searchTerm: searchTerm) }
This will fix the timeout error from the type inference engine. It is also more readable, more understandable, and more maintainable.
Extended syntax
Try the extended syntax
workArray.filter { elm -> Bool in
// put your conditions here
}
this way you are helping the compiler to understand that the closure receive an element of the type of your array and returns a Bool value.
I am new to swift and trying to solve a very basic Logical AND problem
if (textField == self.cvv && cvv.text.length == 4 && !string.isEmpty)
{
return false;
}
this is my code
According to this
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html
the && does exists however I am getting error
Couldn't find an overload for the &&
What and how can I use logical operations?
It is not a logical && error: compiler confused by an earlier error:
'String' does not have a member named 'length'
count(cvv.text) is not available either:
See #RMenke's answer for Swift 2.0 syntax.
I just tried this:
var textField = UITextField()
var cvv = UITextField()
var string = ""
if (textField == cvv && cvv.text!.characters.count == 4 && string.isEmpty)
{
return false;
}
I couldn't replicate the error, because I have no idea about the types and declarations of all instances involved. However I got an error on the text.length might be a Swift 1.2 => swift 2.0 change. I updated it to text.characters.count
To more fully answer your question...
&& always worked fine for me, exactly the way you use it.
conditon1 operatorA condition2 && condition3 operatorB conditon4 ...
However the "couldn't find an overload" error is often the result of a type mismatch. Checking an Int against a String for example.
I'm trying to create an iPhone app that takes the user's response to four criteria and, based on that, shows a specific set of data related to that permutation of answers. For example, in the main view controller:
User selects A or B in a segmented controller (let's say they choose A)
User selects C or D in a segmented controller (they choose D)
User selects E or F in a segmented controller (they choose E)
User inputs an age in a text box (they type in 37)
User touches the "Get Numbers" button
Based on the combination of "A, D, E, 37", the view that appears on the touch of "Get Numbers" shows an image overlaid with seven labels containing the numbers 17.1, 14.2, 30.0, 60.4, 18.1, 19.7 and 80.2. If the user had selected a different set of responses on the main controller, a different set of numbers would appear in those same labels.
I've researched the various elements, but I can't figure out how to combine them to produce the desired outcome. How can I do this? Any advice would be much appreciated--I'm quite new to xCode and completely stuck.
Thanks
I do not actually program in Xcode or Objective-C, but it seems to me that you are looking for a CASE statement. I found the following links, I hope they help:
the best way to implement readable switch case with strings in objective-c?
http://www.techotopia.com/index.php/The_Objective-C_switch_Statement
Based on your question, this is all contained in one viewController so you shouldn't need to pass a bunch of properties. The hard part is knowing how you are attempting to mutate the values and how much branching needs to happen. Also, you have 7 return values and there's no way of knowing how to compute these, like if the output from the first response is calculated with the second and third responses, etc.
EDIT, after reading your comment:
There are 8 possible outcomes, maybe you can create 8 methods to deal with each one. I can't think of any other way, but correct me if I'm wrong:
Possible values:
{
(A,C,E) ;
(B,C,E) ;
(A,D,E) ;
(B,D,E) ;
(A,C,F) ;
(B,C,F) ;
(A,D,F) ;
(B,D,F) ;
}
//Do it with an IF statement:
//first capture state into BOOL values
BOOL a = NO;
BOOL c = NO;
BOOL e = NO;
if (abSegment.selectedSegmentIndex == 0) { a = YES; }
if (cdSegment.selectedSegmentIndex == 0) { c = YES; }
if (efSegment.selectedSegmentIndex == 0) { e = YES; }
//next do some matching with IF statements
if (a && c && e) {
//do something for A,C,E
}
if (!a && c && e) {
//do something for B,C,E
}
if (a && !c && e) {
//do something for A,D,E
}
if (!a && !c && e) {
//do something for B,D,E
}
if (a && c && !e) {
//do something for A,C,F
}
if (!a && c && !e) {
//do something for B,C,F
}
if (a && !c && !e) {
//do something for A,D,F
}
if (!a && !c && !e) {
//do something for B,D,F
}
If you have hardcoded values you can just write the label updating text inside each IF block that matches your requirements. It's hacky but it's all I can think of right now