- If and If Else: AppleScript Conditional Statements
- Diving Deep into AppleScript
- What If?
- Boolie What Now?
- How Conditionals Use Booleans
- Single Line Conditionals
- Else If
- Leaner Code is Better
- This or That?
- Stay Tuned
- Question: Q: how to use the if = function in numbers?
- Helpful answers
- Conditionals in Swift with If, Else If, Else
- Conditional Branching with The “if” Statement
- Expressions and Boolean Logic
- Comparison Operators in Swift
- Logical Operators: AND, OR, NOT
- How To Use “if”, “else if” and “else”
- Further Reading
If and If Else: AppleScript Conditional Statements
Conditional statements are the backbone of many programming and scripting languages. In AppleScript, they provide a way for you to add another dimension of complexity to your scripts by analyzing and responding to various situations. This tutorial will take a close look at if and if else statements and the various ways to implement them in a script.
Diving Deep into AppleScript
Thus far we’ve posted two articles that are perfect for taking you from a complete novice to someone who can competently work your way around a basic script:
These tutorials serve as an overview and give you a good idea of how AppleScript works as well as what types of programming structures are involved. If you’re really intent on becoming a master script writer though, you’re going to have to go much deeper into the syntax and constructs that make up AppleScript.
Don’t worry, we’re with you every step of the way. This is the first in a series of articles that’s going to take a long hard look at different aspects of AppleScript so that you can leverage its awesome power to automate your Mac.
Tip: To run the scripts in this post, you’ll need to open the «AppleScript Editor» app, which can be found in Applications>Utilities.
What If?
In AppleScript, you’ll be hard pressed to find two characters that rival the power of «if». If you learn to properly wield this seemingly simple tool, you’ll go far.
A basic if statement works a lot like a tell block. Just for a refresher, here’s the structure of a tell:
[applescript]
tell application «Safari»
activate
end tell
[/applescript]
As you can see, this script launches Safari. It has three lines: the first and last comprise the tell «block», which must always contain an end statement. Everything between these two lines makes up the body of the tell block.
Conditional statements, as well as many other constructs, borrow this same structure, only this time around we use if instead of tell.
[applescript]
if true then
—do something
end if
[/applescript]
This structure is pretty straightforward and should make perfect sense. First, you start your conditional statement and you qualify it with a boolean, then you write your commands that trigger in the case of a truth, and finally, you close off your statement with an end.
Tip: In AppleScript Editor, you don’t need to type out «end if», just «end». The compiler will automatically add the rest, even if you have multiple end statements that belong to different types of blocks. It figures it all out for you!
Boolie What Now?
Before we go any further, it’s absolutely critical that you understand exactly what I mean when I refer to a boolean. Boolean is a data type that can only have one of two values: true or false. In the world of computing, absolutes absolutely exist. Either something is, or it isn’t, there’s no in between.
AppleScript can easily figure out if certain things are true and use this knowledge to power a conditional statement. To try it out, try typing in an equality statement right into AppleScript Editor and running it.
As you can see, the compiler evaluated the statement, «10 > 1», and correctly returned «true». If we flip that equality symbol around and run «10
How Conditionals Use Booleans
Now that you understand what a boolean is, it’s easier to wrap your mind around how conditionals work. As we saw in the chart above, a conditional statement says, «if this boolean evaluates as true, then do something.»
Let’s see this in practice using the «10 > 1» statement that we tested earlier:
[applescript]
if 10 > 1 then
return «That’s right!»
end if
[/applescript]
Here we’ve replaced the word «true» with something that we want AppleScript to evaluate. The structure here is exactly what we saw before:
Given this structure, the commands inside of the if statement will only execute if the boolean proves to be true. In this case, the statement is true, so we’ll see the following in the «Result» portion of the AppleScript Editor window.
Single Line Conditionals
In case you’re wondering, there is a special, succinct form of an if statement that only occupies a single line. It does not require an «end» and can’t take any of the added complexity that we’re going to look at in the next section, but it’s useful for simple cases.
[applescript]
—Single line if statement
if 10 > 2 then return «yes»
[/applescript]
If statements are awesome, but they’re a bit limited in the form that we’ve seen thus far. For instance, what if the boolean in the script turned out to be false? Here’s an example:
[applescript]
set x to 20
if 10 > x then
return «10 is greater than » & x
end if
[/applescript]
As you can see, I’m gradually increasing the complexity here so that you become more familiar with common patterns and constructs. In this example, we first set up a variable, x, then set that variable equal 20. Now when we run our if statement, the number 10 is compared to the variable.
In this case, 10 is not greater than 20, so the boolean will be false. This means that our script won’t do anything at all! To fix this problem, we turn to else. Let’s modify our script a bit:
[applescript]
set x to 20
if 10 > x then
return «10 is greater than » & x
else
return «10 is not greater than » & x
end if
[/applescript]
The great thing about AppleScript is that it’s so human readable. If you simply read this script out loud, you’ll be able to tell exactly what it does. Here’s the rundown:
- Assigns a value of 20 to x
- Compares the number 10 to x to see if 10 is greater
- If 10 > x, return the following statement
- If not (else), return this other statement instead
Given that 10 is not greater than 20, the second statement will be returned. Your result should look something like this:
Now that we can account for two different boolean scenarios, we are much more suited to tackle complex scripting challenges.
Else If
As you can imagine, even this isn’t enough to account for all of the different situations that you’re going to run into. Perhaps we have a fairly complex scenario that where a number of different outcomes is possible.
In this scenario, we can implement else if to continue adding complexity to our if statement. Consider the following:
[applescript]
set theWeekDay to weekday of (current date)
if (theWeekDay = Friday) then
return «You’re almost free!»
else if (theWeekDay = Saturday) then
return «It’s the weekend!»
else if (theWeekDay = Sunday) then
return «Relax, for tomorrow we work.»
else
return «Hang in there, it’s not the weekend yet!»
end if
[/applescript]
Once again, even if you’re not familiar with AppleScript, the natural language makes it pretty easy to figure out what’s going on. First, we set a variable to the current weekday. Next, we run through a series of tests using if, else if and else to arrive at an appropriate return message given the current day of the week.
On run, the script will try the first if statement. If that proves true, the first return statement will be run and the script will terminate (no further steps are taken). However, if that statement proves false, the first else if is tried, then the second and finally, if none of those prove true, the last else kicks in and returns a statement about it not being the weekend yet.
Leaner Code is Better
The else if structure is incredibly powerful and allows you to account for any number of different scenarios. As you code up certain projects, you might be tempted at times to chain together five, ten or even fifteen else if statements to cycle through all of the available possibilities. Unfortunately, this isn’t typically a good way to code and can lead to a ton of unneeded bloat.
Always be mindful when using else if and ask yourself whether or not there’s a better way to go about what you’re trying to accomplish. It’s often far more practical and brief to use a loop of some kind, but that’s an article for another day (coming soon!).
This or That?
One last quick piece of advice regarding if statements. One alternative to else is to use or instead. Here’s a simplified version of the weekday script using or and only two possible return statements.
[applescript]
set theWeekDay to weekday of (current date)
if (theWeekDay = Saturday) or (theWeekDay = Sunday) then
return «It’s the weekend!»
else
return «Hang in there, it’s not the weekend yet!»
end if
[/applescript]
Stay Tuned
This covers most of what you need to know about conditionals. Crack open AppleScript Editor and start experimenting with your own conditional statements. What cool scripts can you come up with?
This is just the tip of the proverbial iceberg as far as our coverage of AppleScript. This is an incredibly expansive topic that has a lot of potential to increase your mastery over your Mac, so we’re going to have lots more great AppleScript tutorials to help you become a true automation expert.
Источник
Question: Q: how to use the if = function in numbers?
In numbers, I’m trying to design a table that includes the if/or with > A2,3) it works I input the data and got the correct info. My problem i.e. =if(B1=B2,1) not data the cell already has the 1. How can I solve the issue? My assumption is that the system reads empty cells (no data) as equals;therefore, the formula reads it as equal none value giving me: 1
Posted on Dec 5, 2013 6:26 PM
Helpful answers
The if() function actually takes three arguments:
IF ( if-expression, if-true , if-false )
- if-expression: A logical expression. if-expression can contain anything as long as the expression can be evaluated as a boolean value. If the expression evaluates to a number, 0 is considered to be FALSE, and any other number is considered to be TRUE.
- if-true: The value returned if if-expression is TRUE. if-true can contain any value . If if-true is omitted (there’s a comma, but no value) and if-expression evaluates to TRUE, IF will return 0.
- if-false: An optional argument specifying the value returned if if-expression is FALSE. if-false can contain any value. If if-false is omitted (there’s a comma, but no value) and if-expression evaluates to FALSE, IF will return 0. If if-false is entirely omitted (there’s no comma after if-true ) and if-expression evaluates to FALSE, IF will return FALSE.
you are leaving the if-false portion blank.
so if you want nothing when the boolean test is false you should enter the empty string for the third argument like:
if you do not want any result when either cell is blank you can perform the test:
=if(or(isblank(B1), isblank(B2)), «», if(B1=B2, 1, «»))
Источник
Conditionals in Swift with If, Else If, Else
You use conditionals to make decisions in your Swift code, with if , else if and else . If this happens, then do that. This is called control flow, because you use it to control the way your code flows.
In this tutorial you’ll learn how to use the if -statement in your Swift code. We’ll get into boolean logic, expressions, operators, and the syntax of if , else if and else blocks.
In practical iOS development you use conditionals all the time. Logic expressions can be especially hard to grasp, but after completing this tutorial you’ll be well equipped to deal with even the most challenging conditionals.
Conditional Branching with The “if” Statement
Conditionals, branching, if-statements – they all mean the same thing: taking decisions in your code. Like this:
if this happens, then do that
- If the user is logged in, then load her tweets
- If the tweet includes a photo, then use the MediaTweet UI
- If the tweet text is not empty, then process the tweet’s hashtags
Making decisions like these is called control flow, or branching, because you split the flow of your code in separate branches.
Imagine you create many of these decisions like the one above, and you see that the flow of your code quickly branches out in many directions. Kinda like a tree!
Let’s take a look at the Swift syntax for conditionals. Here’s an example:
A few things are happening here:
- The expression password == «Open sesame!» uses boolean logic to determine whether the variable password is equal to the string Open sesame!
- When this expression evaluates to true , the code between the squiggly brackets < and >is executed. This is the conditional body.
In other words: if the password is “Open sesame!” then open the cave and steal the treasure!
You’ve seen those squiggly brackets < and >before, in functions and in classes. They’re used throughout programming to structure blocks of code. Whenever a function is called, or a conditional is true , the block of code between < and >is executed.
Expressions, like password == «Open sesame!» , are more complicated. Let’s figure out how that works, in the next chapter.
Expressions and Boolean Logic
If you’re familiar with math, you know that the expression 3 + 4 + 5 produces the result 12 . In programming, you can create expressions too:
The expression 2 * .pi * radius produces the circumference of a circle, based on its radius . The result of the expression is 94.24 in the following example:
let radius = 15.0
let circumference = 2 * .pi * radius
An expression is a combination of one or more values, constants, variables, operators, and functions that Swift interprets and computes to produce a return value. This process is called evaluation.
Said differently: you can combine numbers, variables and functions to create an expression of a particular value. This value can then be assigned to a variable, like circumference and radius in the example above.
One kind of expression is exceptionally powerful: the boolean expression. This expression uses boolean logic to return either true or false . Its type in Swift is Bool .
Let’s look at an example:
let isLoggedIn:Bool = false
if isLoggedIn <
print(«*** SECRET MESSAGE ***»)
>
Use the Swift Sandbox above to do this:
- First, run the Sandbox by clicking Play
- Then, change the value of isLoggedIn to true
- Finally, run the Sandbox again
Did you see what happened?
- If isLoggedIn is false , the conditional is not executed, and the secret message is not shown
- If isLoggedIn is true , the conditional is executed, and the secret message is shown
That’s boolean logic right there! The if-statement evaluates the value of isLoggedIn and acts accordingly. When the value is true , the conditional body is executed. When the value is false , the conditional body is not executed.
You don’t only use conditionals to check for UI/UX logic in your code, such as “is the user logged in” or “is the password correct”. You also use conditionals to check the state of your code, and to validate data that’s passed around.
Imagine the following scenario:
- Your UI has two buttons: loginButton and signupButton
- You use one function to respond to taps on both buttons, called onButtonTapped(button:)
- Inside the function you compare the button parameter against the loginButton and the signupButton with:
- Now you know which button was tapped, and you can act accordingly
This conditional has nothing to do with interactions in your app. It acts upon the data within your code. Let’s look at some more advanced examples of conditionals, in the next chapters.
Why is it called boolean logic? It’s named after mathematician George Boole (1815-1864), who laid the groundwork for Boolean algebra. Boolean expressions produce either true or false , called truth values, often denoted as 1 or 0 respectively. These two values lie at the basis of digital systems, like computers and apps.
Comparison Operators in Swift
Do you see that == ? It’s a comparison operator, and you use it to check if two values are equal.
Swift has the following comparison operators:
- Equal to: a == b
- Not equal to: a != b
- Greater than: a > b
- Less than: a
- Greater than or equal to: a >= b
- Less than or equal to: a
You use comparison operators to compare values with each other. You typically use > , , >= and with numerical values, whereas == and != are typically used to find out if any two values are the same or not.
Swift also has two identity operators, === and !== , that test if two references both refer to the exact same object.
Let’s look at an example:
if room >= 100 <
print(«This room is on the first floor. «)
>
The expression room >= 100 tests if the constant room is greater than or equal to 100 . Because room is 101 , the expression returns true and the conditional body is executed. Can you change the code to something else, to see how it works?
When you compare two values, they both need to have the same type. It does not make sense to test if a string is equal to an integer. They’ll never be equal, because they both have different types. An exception to this rule would be comparing compatible number types, like integers and doubles, with each other.
The code below results in a compiler error, because room and input have different types.
let room:Int = 123
let input:String = «123»
if room == input <
print(«This room is available!»)
>
What if you need to compare a string value with an integer value? You’ll need to parse the string and convert it to an integer, or convert the integer to a string. When both types are related, you can also use type casting.
You already know about optionals in Swift, right? You can use the equality operators == and != to compare an optional with a non-optional value, but you can’t use > , , >= and to compare optionals without unwrapping them.
Interestingly, you can compare strings with each other, using all of the == , != and even > , , >= , operators! So we can test whether “abcd” is less than “efgh”. Like this:
This is exceptionally useful for sorting string values, for instance to order names alphabetically:
Alright, let’s move on to the next set of operators!
Logical Operators: AND, OR, NOT
A boolean expression with just one condition is a bit boring, so let’s spice it up with the logical operators AND, OR and NOT.
var isPresident = true
var threatLevel = 7
var officerRank = 3
if (threatLevel > 5 && officerRank >= 3) || isPresident
<
print(«FIRE ROCKETS. «)
>
In the above example, you can fire rockets if…
- … isPresident is true OR
- … threatLevel is greater than 5 AND officerRank is greater than or equal to 3
See how you’re using logical operators to create a combination of boolean expressions? You’re also using comparison operators to assess the value of threatLevel and officerRank .
There are 3 different logical operators:
- AND, denoted by &&
- OR, denoted by ||
- NOT, denoted by !
Both AND and OR are infix operators, so you put the operator between two values, like a && b and a || b . The NOT operator is a prefix, so you put it before one value, like !a .
Here’s what these operators do:
- An expression with the AND operator returns true when both of its operands are true . When either operand is false , it returns false .
- An expression with the OR operator returns true when either of its operands are true . When both are false , the OR operator returns false .
- An expression with the NOT operator returns the opposite of its value, so true when false , and false when true .
What are operands? In an expression a + b , the + is the operator, and a and b are operands. The operator affects the operands.
That’s complicated stuff, right? Let’s put those expressions in a Truth Table, like this:
a | b | AND | OR |
---|---|---|---|
true | true | true | true |
true | false | false | true |
false | true | false | true |
false | false | false | false |
The result in the “AND” and “OR” columns is based on the result of the expression a x b , where “x” is either AND or OR. It’s the output based on the operators and a and b .
You can read the Truth Table like this:
- Row 1: When both a and b are true , both AND and OR return true
- Row 2-3: When a is true and b is false , or vice versa, AND returns false and OR returns true
- Row 4: When both a and b are false , both AND and OR return false
And a Truth Table for the NOT operator is simple, like this:
a | NOT |
---|---|
true | false |
false | true |
The NOT operator inverts true and false . So when a = false , the expression !a returns true . This is exactly the same as a == false , which also returns true .
Can you ascertain the result of the expression !(! false ) ? It’s not not false, which is not true, which is false. Mind-boggling!
That’s quite theoretical, so let’s put it into practice. We’re going to play around with the previous example, this one:
var isPresident = true
var threatLevel = 7
var officerRank = 3
if (threatLevel > 5 && officerRank >= 3) || isPresident
<
print(«FIRE ROCKETS. «)
>
You can break that expression down in two parts. We’ll start at the deepest level, inside the parentheses:
This expression combines two expressions, namely threatLevel > 5 and officerRank >= 3 . They’re connected with the AND logical operator. So, the entire expression will only result in true when both the threatLevel is greater than 5 and the officerRank is greater than or equal to 3 .
The second part of the expression is this:
In the above code “X” is the result of the previous expression threatLevel > 5 && officerRank >= 3 . We’re combining the result of that expression with isPresident and the OR operator || .
When either of the expressions threatLevel > 5 && officerRank >= 3 or isPresident is true , the entire expression returns true .
Consider that treatLevel = 7 , officerRank = 3 and isPresident = true . We can then resolve every expression step by step, like this:
What if threatLevel = 4 , officerRank = 5 and isPresident = false ? Then you can evaluate the expressions like this:
See how that works? Awesome!
Important question: If isPresident is true , does it matter what the threatLevel and the officerRank is? (Answer for yourself! Correct answer at end of tutorial.)
How To Use “if”, “else if” and “else”
Alright, last but not least: the syntax for if , else if and else . You can combine multiple conditionals into one chain. Like this:
let color = «purple»
if color == «green»
<
print(«I love the color \(color)!»)
>
else if color == «blue» || color == «purple»
<
print(«I kinda like the color \(color). «)
>
else
<
print(«I absolutely HATE the color \(color). «)
>
In the above example you’ve combined several if-statements into one conditional, using if , else if and else . Here’s how it works:
- First, you declare a constant color of type String , and assign the string «purple» to it.
- Then, the expression color == «green» is evaluated. When that expression results in true , the first < >block is executed, and every other expression after that is skipped. When the expression results in false , the first < >block is not executed, and the code continues to evaluate the next expression.
- Assuming that the previous expression returned false , the expression color == «blue» || color == «purple» is evaluated. When it returns true , the code block is executed, and when it is false , the code continues to evaluate the next expression.
- Assuming that none of the previous expressions returned true , the else block is invoked. This is a “catch all” when all the other conditional expressions failed, and returned false .
You can deduce a few rules about if , else if and else from the above examples.
- Execution of the conditional starts at the top, and continues to the bottom
- When an expression returns true , that conditional body is executed, and the others are skipped over
- When an expression returns false , the conditional body is skipped over, and the next expression is evaluated
- When none of the expressions have returned true , the else block is executed
Conditionals like the one above are not evaluated “as a whole”. Instead, their expressions are evaluated one by one, from top to bottom.
A conditional needs to include at least one if statement. It can optionally include one else statement, and it can optionally include one or more else if statements.
Let’s look at another example:
let isLoggedIn = false
if isLoggedIn <
print(«*** SECRET MESSAGE ***»)
> else <
print(«ACCESS DENIED!»)
>
In the above example, the else block is executed, because isLoggedIn is false . Said differently: isLoggedIn is not true , so the first block is not executed, and consequently the else block is executed.
A common misconception is that an else block is executed when the expression in the first block is false . This is a correct assertion in the above example. But what about the following code…
In this example, the else block is executed for any value of name that is not «Bob» . The else block is really a “catch all” for when all of the earlier expressions failed.
OK, let’s look at one last example:
var isPresident = true
var threatLevel = 7
var officerRank = 3
if threatLevel > 5 && officerRank >= 3 <
print(«FIRE ROCKETS. (as officer)»)
> else if isPresident <
print(«FIRE ROCKETS. (as president)»)
> else <
print(«CANNOT FIRE ROCKETS. «)
>
The above example has the exact same effect as the previous examples, except that its implementation is now different. Do you see the difference?
Instead of firing rockets when the threatLevel , officerRank and isPresident variables have the correct values, you now respond to individual cases. As a result, only one of these conditionals is executed.
Here’s a few things you can try:
- Can you switch the threatLevel . and isPresident expressions? How does that affect execution?
- Imagine that both a president and a high-ranking officer have their hand on the rocket launch button. Who presses it first?
- Can you break up the threatLevel > 5 && officerRank >= 3 in two else if expressions? Does this affect the conditions under which a rocket launch is allowed?
- Do you know when the else clause will be executed, based on the state of the 3 variables?
Further Reading
Conditionals are awesome, right? If this happens, then do that. You use that to take decisions in your code, and to “branch out” into different states and scenarios.
This is what you’ve learned:
- How to use conditionals with if to take decisions in your code
- How boolean expressions affect the execution of conditionals
- How to use logical operators and comparison operators
- How the syntax of if , else if and else works
Want to learn more? Check out these resources:
Answer: When isPresident is true , it does not matter what threatLevel and officerRank are. The expression a || b returns true if a or b is true , and it doesn’t matter which one. However, in the else if example, when the threatLevel and officerRank are high enough, the officer will launch the rockets before the president, even when isPresident is true.
Источник