0

A few days ago, I posted a Swift question (Using Switch with Arrays) and quickly got back a beautiful answer. Ever since, ​I have been trying to decompose in my mind just how this statement:

case let word where excludedWords.contains(word): 

is parsed and executed by Swift. It would seem to me that the 'let word...' portion is evaluated first, and for each occurrence of a word in excludedWords, Swift passes it back to the case for evaluation. I have not found any documentation, Apple or otherwise, that explains exactly how this works.

Can someone offer me a detailed explanation of just how this construct works in Swift?

1 Answer 1

2

From the language reference (jump to the Switch statement section):

A switch case can optionally contain a where clause after each pattern. A where clause is introduced by the where keyword followed by an expression, and is used to provide an additional condition before a pattern in a case is considered matched to the control expression. If a where clause is present, the statements within the relevant case are executed only if the value of the control expression matches one of the patterns of the case and the expression of the where clause evaluates to true.

I will include the answer to your other question here for context:

switch eachWord { case let word where excludedWords.contains(word): // Do Something default: // Do another thing } 

The execution would go like this:

  1. let word = eachWord
  2. Test if excludedWords.contains(word) == true
  3. If it is, execute the branch. Otherwise, go to the default branch
Sign up to request clarification or add additional context in comments.

2 Comments

I fully understand the inner workings of the switch statement; I was having difficulty wrapping my mind around how the 'let word' clause works within the context of the switch. The part of your explanation "If a where clause is present, the statements within the relevant case are executed only if the value of the control expression matches one of the patterns of the case and the expression of the where clause evaluates to true." was the missing piece to helping me finally GET it. Many thanks!
In this case it actually works exactly like a simple if-else but introducing additional variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.