Time remaining:
How to use the conditional operator?

Computer Science
Tutor: None Selected Time limit: 0 Hours

in XCode

Nov 19th, 2014

Basic Operators

An operator is a special symbol or phrase that you use to check, change, or combine values. For example, the addition operator (+) adds two numbers together (as in let i = 1 + 2). More complex examples include the logical AND operator && (as in if enteredDoorCode && passedRetinaScan) and the increment operator ++i, which is a shortcut to increase the value of i by 1.

Swift supports most standard C operators and improves several capabilities to eliminate common coding errors. The assignment operator (=) does not return a value, to prevent it from being mistakenly used when the equal to operator (==) is intended. Arithmetic operators (+-*/% and so forth) detect and disallow value overflow, to avoid unexpected results when working with numbers that become larger or smaller than the allowed value range of the type that stores them. You can opt in to value overflow behavior by using Swift’s overflow operators, as described in Overflow Operators.

Unlike C, Swift lets you perform remainder (%) calculations on floating-point numbers. Swift also provides two range operators (a..<b and a...b) not found in C, as a shortcut for expressing a range of values.

This chapter describes the common operators in Swift. Advanced Operators covers Swift’s advanced operators, and describes how to define your own custom operators and implement the standard operators for your own custom types.

Overflow Operators.

The addition operator is also supported for String concatenation:

  • "hello, " + "world" // equals "hello, world"

Expressions.

Classes and Structures.

Each of the comparison operators returns a Bool value to indicate whether or not the statement is true:

  • 1 == 1 // true, because 1 is equal to 1
  • 2 != 1 // true, because 2 is not equal to 1
  • 2 > 1 // true, because 2 is greater than 1
  • 1 < 2 // true, because 1 is less than 2
  • 1 >= 1 // true, because 1 is greater than or equal to 1
  • 2 <= 1 // false, because 2 is not less than or equal to 1

Comparison operators are often used in conditional statements, such as the if statement:

  • let name = "world"
  • if name == "world" {
  • println("hello, world")
  • } else {
  • println("I'm sorry \(name), but I don't recognize you")
  • }
  • // prints "hello, world", because name is indeed equal to "world"

For more on the if statement, see Control Flow.

Control Flow.

Arrays.

Logical Operators

Logical operators modify or combine the Boolean logic values true and false. Swift supports the three standard logical operators found in C-based languages:

  • Logical NOT (!a)

  • Logical AND (a && b)

  • Logical OR (a || b)

Logical NOT Operator

The logical NOT operator (!a) inverts a Boolean value so that true becomes false, and false becomes true.

The logical NOT operator is a prefix operator, and appears immediately before the value it operates on, without any white space. It can be read as “not a”, as seen in the following example:

  • let allowedEntry = false
  • if !allowedEntry {
  • println("ACCESS DENIED")
  • }
  • // prints "ACCESS DENIED"

The phrase if !allowedEntry can be read as “if not allowed entry.” The subsequent line is only executed if “not allowed entry” is true; that is, if allowedEntry is false.

As in this example, careful choice of Boolean constant and variable names can help to keep code readable and concise, while avoiding double negatives or confusing logic statements.

Logical AND Operator

The logical AND operator (a && b) creates logical expressions where both values must be true for the overall expression to also be true.

If either value is false, the overall expression will also be false. In fact, if the first value is false, the second value won’t even be evaluated, because it can’t possibly make the overall expression equate to true. This is known as short-circuit evaluation.

This example considers two Bool values and only allows access if both values are true:

  • let enteredDoorCode = true
  • let passedRetinaScan = false
  • if enteredDoorCode && passedRetinaScan {
  • println("Welcome!")
  • } else {
  • println("ACCESS DENIED")
  • }
  • // prints "ACCESS DENIED"

Logical OR Operator

The logical OR operator (a || b) is an infix operator made from two adjacent pipe characters. You use it to create logical expressions in which only one of the two values has to be true for the overall expression to betrue.

Like the Logical AND operator above, the Logical OR operator uses short-circuit evaluation to consider its expressions. If the left side of a Logical OR expression is true, the right side is not evaluated, because it cannot change the outcome of the overall expression.

In the example below, the first Bool value (hasDoorKey) is false, but the second value (knowsOverridePassword) is true. Because one value is true, the overall expression also evaluates to true, and access is allowed:

  • let hasDoorKey = false
  • let knowsOverridePassword = true
  • if hasDoorKey || knowsOverridePassword {
  • println("Welcome!")
  • } else {
  • println("ACCESS DENIED")
  • }
  • // prints "Welcome!"

Combining Logical Operators

You can combine multiple logical operators to create longer compound expressions:

  • if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
  • println("Welcome!")
  • } else {
  • println("ACCESS DENIED")
  • }
  • // prints "Welcome!"

This example uses multiple && and || operators to create a longer compound expression. However, the &&and || operators still operate on only two values, so this is actually three smaller expressions chained together. The example can be read as:

If we’ve entered the correct door code and passed the retina scan, or if we have a valid door key, or if we know the emergency override password, then allow access.

Based on the values of enteredDoorCodepassedRetinaScan, and hasDoorKey, the first two mini-expressions arefalse. However, the emergency override password is known, so the overall compound expression still evaluates to true.

Explicit Parentheses

It is sometimes useful to include parentheses when they are not strictly needed, to make the intention of a complex expression easier to read. In the door access example above, it is useful to add parentheses around the first part of the compound expression to make its intent explicit:

  • if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
  • println("Welcome!")
  • } else {
  • println("ACCESS DENIED")
  • }
  • // prints "Welcome!"

The parentheses make it clear that the first two values are considered as part of a separate possible state in the overall logic. The output of the compound expression doesn’t change, but the overall intention is clearer to the reader. Readability is always preferred over brevity; use parentheses where they help to make your intentions clear.


Nov 19th, 2014

Did you know? You can earn $20 for every friend you invite to Studypool!
Click here to
Refer a Friend
...
Nov 19th, 2014
...
Nov 19th, 2014
Dec 9th, 2016
check_circle
Mark as Final Answer
check_circle
Unmark as Final Answer
check_circle
Final Answer

Secure Information

Content will be erased after question is completed.

check_circle
Final Answer