Introduction to Swift

Operators and Control Flow in Swift

programming language construct that performs actions according to boolean conditions

Programming language construct that performs actions according to boolean conditions.

Operators in Swift

Operators are special symbols or phrases that you use to check, change, or combine values. Swift supports most standard C operators and improves several capabilities to eliminate common coding errors. The assignment operator = doesn’t return a value, to prevent it from being mistakenly used when the equal to operator == is intended.

Arithmetic Operators

Swift supports the four standard arithmetic operators for all number types:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)

Comparison Operators

Swift supports all standard C comparison operators:

  • Equal to (==)
  • Not equal to (!=)
  • Greater than (>)
  • Less than (<)
  • Greater than or equal to (>=)
  • Less than or equal to (<=)

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)

Range Operators

Swift includes two range operators, which are shortcuts for expressing a range of values.

  • Closed Range Operator (a...b)
  • Half-Open Range Operator (a..<b)

Compound Assignment Operators

Like C, Swift provides compound assignment operators that combine assignment (=) with another operation. An example is the addition assignment operator (+=).

Ternary Conditional Operator

The ternary conditional operator is a special operator with three parts, which takes the form question ? answer1 : answer2. It’s a shortcut for evaluating one of two expressions based on whether question is true or false.

Control Flow in Swift

Control flow statements are used to control the flow of execution in a program.

Conditional Statements

Swift has two types of conditional statements that include if and switch.

Loop Statements

A loop is a block of code that’s executed repeatedly, either a specified number of times or until a certain condition is met. Swift has three kinds of loops for-in, while and repeat-while.

Control Transfer Statements

Control transfer statements change the order in which your code is executed, by transferring control from one piece of code to another. Swift has five control transfer statements: continue, break, fallthrough, return, and throw.

By understanding and using these operators and control flow statements, you can control the logic and execution of your Swift code effectively.