Swift Review — Control Flow

source: https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html

We try to summarize briefly aboutswitch and guard clauses

  1. switch
  • Switch clauses in Swift have two noticeable features: exhaustive cases(so it is common to add default case)and no implicit fallthrough(no need to use `break` for every case, but sometimes it is necessary -> when we need to ignore some cases(this is due to the exhaustiveness). Also, overlapping cases are allowed but only the first matching case is executed)
  • special cases: interval matching / tuples / compound cases(enumerating cases with comma “,”)
  • However, we can use fallthrough keyword to explicitly use the fallthrough functionality such as in C

2. guard( = early exit)

  • an explicit statement of guard-clause, which is usually implemented only with if-clause in other languages
guard condition else { // a statement that exit the block }// usually we put let varname in the condition
  • if the condition is true, the variables in it can be used as a non-optional variable throughout the block
  • if not, else-clause is executed and the whole remaining block is ignored(so we must write down else { } when we use guard-clause)