What are the different control transfer statements used in Swift?

Swift language consists of following Control transfer statements:

  • Continue
  • Break
  • Fallthrough
  • Return

In Swift, there are several control transfer statements that you can use to control the flow of your code. These include:

  1. return: Used to return a value from a function, method, or closure.
  2. break: Terminates the execution of a loop, switch statement, or labeled statement.
  3. continue: Skips the rest of the current iteration of a loop and begins the next iteration.
  4. fallthrough: Used within a switch case to transfer control to the next case in a switch statement. It’s not commonly used.
  5. throw: Throws an error to indicate that a function or method has encountered a problem.
  6. try: Used to handle errors in Swift, typically used with error handling constructs like do-catch or try?.
  7. guard: Provides an early exit from a function, method, or loop if a condition is not met. It’s commonly used for optional unwrapping and validation.
  8. defer: Defers the execution of a block of code until the current scope is exited. It’s often used for cleanup tasks.

These control transfer statements provide powerful mechanisms for controlling the flow of your Swift code.