FAQ: Conditionals - Switch Statement: where Clause

This community-built FAQ covers the "Switch Statement: where Clause " exercise from the lesson “Conditionals”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Swift

FAQs on the exercise _Switch Statement: where Clause _

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in Language Help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

Looking for motivation to keep learning? Join our wider discussions in Community

Learn more about how to use this guide.

Found a bug? Report it online, or post in Bug Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

If a switch statement actually checks against the values of the cases, then a where clause shouldn’t work since something like wholeNumber is not equal to let x where x % 2 == 0 (which I’d think would be a boolean). It must be more complicated than that. I know that it works, but I still wonder how it works. To be fair, items separated by commas are checked against individually, and you don’t check against a range, you check if the value is inside the range.

I added a print statement into the beginning with the random generator. This shows the number then runs the code.

var wholeNumber = Int.random(in: 1...30)
  print("The Number is \(wholeNumber)")

switch wholeNumber {
  case let x where x % 2 == 0:
    print("Composite")
  case let x where x % 3 == 0:
    print("Composite")
  default:
    print("Prime")
}

Why are the cases “== 0”? If you divide 15 by either 2 or 3, you shouldn’t get 0. Obviously I’m missing something here, lol…

% is different from /. While / is the division operator, the modulo operator (%) returns the remainder of a division operation. If a % b == 0, then a is evenly divisible by b (no remainder). More on operators here.

Example

10 / 2 = 5
10 % 2 = 0

Welcome to the forums!

1 Like

Two questions…

  1. How come we are allowed to assign x or y or really anything as a temporary variable to let?
    For instance, what is the difference in using
case let randomNumber where randomNumber % 2 == 0:
vs
case let x where x % 2 == 0:

in the code

var randomNumber = Int.random(in: 0...10) print(randomNumber) switch randomNumber { case let randomNumber where randomNumber % 2 == 0: print("\(randomNumber) is even") case let randomNumber where randomNumber % 2 == 1: print("\(randomNumber) is odd") default: print("Invalid") }
  1. The other thing is, the console in this Codebyte outputs an error when I use in (as in in: 0...10), but in the lesson, this exact code works fine. What happened?

Thanks in advance!

1 Like

Can i ask why I cant write the expression as is? ie
switch abc {
case abc % 2 == 0:
// above vs below
case let x where x % 2 == 0 :
}

2 Likes

Same question as you here! Anyone?!

1 Like

Seems to be an error with the correct solution.

switch wholeNumber {
case let x where x % 2 == 0:
print("Composite ")
case let x where x % 3 == 0:
print(“Composite”)
default:
print(“Prime”)
}

Notice the additional space after the first “Composite” causes my correct answer to show as incorrect.

Hello everybody,

What I am about to ask, it’s related to the example provided by Codecademy and not the exercise itself.

I know the following code won’t work. But my question is “Why?”

I can’t seem to understand why do we actually need to use the “let x where”. Code as follows:

var randomNumber = Int.random(in: 0…10)

switch randomNumber {
case number % 2 == 0:
print(“(randomNumber) is even”)
case number % 2 == 1:
print(“(randomNumber) is odd”)
default:
print(“Invalid”)
}

Isn’t the number 2 and the number 3 prime numbers?

Codecademy website says this code is correct, so how come is the code saying 2 and 3 are composite?

var wholeNumber = 2

// Write your code below
switch wholeNumber {
case let x where x % 2 == 0:
print(“Composite”)
case let x where x % 3 == 0:
print(“Composite”)
default:
print(“Prime”)
}

1 Like

Your code:

var randomNumber = Int.random(in: 0...10)
 
switch randomNumber {
  case number % 2 == 0:
    print("\(randomNumber) is even")
  case number % 2 == 1:
    print("\(randomNumber) is odd")
  default:
    print("Invalid")
}

What is number? It hasn’t been declared and assigned a value anywhere.
Suppose you re-wrote the cases as:

case randomNumber % 2 == 0:

switch randomNumber is an integer value, whereas randomNumber % 2 == 0 is a boolean.
You will get an error:

error: expression pattern of type ‘Bool’ cannot match values of type ‘Int’

The following will work (as you will be comparing a boolean to a boolean):

var randomNumber = Int.random(in: 0...10)

switch (true) {
  case randomNumber % 2 == 0:
    print("\(randomNumber) is even")
  case randomNumber % 2 == 1:
    print("\(randomNumber) is odd")
  default:
    print("Invalid")
}
1 Like

The instructions specify:

In Numbers.swift, we’ll set up a program that determines if a number between 10 and 20 is prime or composite.

2 and 3 are Prime Numbers, but the code in the exercise is only meant to be used for numbers in the range [10, 20].
The code in the exercise won’t work correctly if number is less than 10 (as you found out) as well as when the number is greater than 20. For example, the exercise code will erroneously identify 25 as a prime number even though 25 is composite.

var wholeNumber = 25
// Switch code here ...

Output: "Prime" // which is wrong as 25 = 5 * 5
///////////////////
var wholeNumber = 49
// Switch code here ...

Output: "Prime" // which is wrong as 49 = 7 * 7
1 Like

Wow, you are absolutely amazing. I tried in different forums and you were the one that got me the right explanation in a way that I can understand.
Also, yes, you are correct, I actually meant “randomNumber” instead of “number”.

Can I post your solution on a post I made on reddit and credit you? Or maybe if you have a reddit acc as well it could be posted there?

I am so grateful, have been trying to understand that for ages!!

1 Like

No credit necessary. Use it as you like.

I cannot understand the function of let x where x in this solution:

var wholeNumber = Int.random(in: 10...20)

switch wholeNumber {
  case let x where x % 2 == 0:
    print("Composite")
  case let x where x % 3 == 0:
    print("Composite")
  default:
    print("Prime")
}

The instructions say that let x temporarily “binds” to wholeNumber. How does it know it has to “bind” to wholeNumber? Does it know that because it’s in the switch statement?

Since that is the case, it would essentially look like:

var wholeNumber = Int.random(in: 10...20)

switch wholeNumber {
  case wholeNumber where wholeNumber % 2 == 0:
    print("Composite")
  case wholeNumber where wholeNumber % 3 == 0:
    print("Composite")
  default:
    print("Prime")
}

I don’t understand how it can function by this logic. Can someone explain this to me like I’m five years old? Why doesn’t the following work? I see the error, but it doesn’t make sense to me. The case statement literally reads “In case wholeNumber divided by 2 has a remainder of 0, print ‘Composite’”:

var wholeNumber = Int.random(in: 10...20)

switch wholeNumber {
  case wholeNumber % 2 == 0:
    print("Composite")
  case wholeNumber % 3 == 0:
    print("Composite")
  default:
    print("Prime")
}
Numbers.swift:6:24: error: expression pattern of type 'Bool' cannot match values of type 'Int'
  case wholeNumber % 2 == 0:

wholeNumber is an integer, whereas     wholeNumber % 2 == 0     and     wholeNumber % 3 == 0     will evaluate to boolean (true/false) values (Is the remainder zero or not? Yes/No? true/false?)

Suppose wholeNumber is 15, does it make sense to compare 15 to the boolean true or false? Hence, the error thrown in the last snippet highlights the mismatch of data types.

Booleans should be compared with booleans, Integers should be compared with integers.

If you want to compare booleans with booleans, then one possible solution is:

var wholeNumber = Int.random(in: 10...20)

switch (true) {
  case wholeNumber % 2 == 0:
    print("Composite")
  case wholeNumber % 3 == 0:
    print("Composite")
  default:
    print("Prime")
}

If you want to compare integers with integers, then the first two solutions (in your post) are doing precisely that. But the first solution involving value bindings (the solution with case let x where ...) allows you to write cases that are less verbose and more readable. The second solution will also work but the first is preferable and potentially less confusing.

In your code,

switch (wholeNumber) {

the switch expression wholeNumber evaluates to an integer. If you declare a variable in your cases, whatever value the switch expression evaluates to will be automatically temporarily bound to the variable declared in your cases. If the expression evaluates to say a tuple, then you can declare multiple variables in your cases and the values will be unpacked automatically based on position. For example,

let threeDimensionalPoint = (3, 0, 1)

switch (threeDimensionalPoint ) {
    case let p where p.0 == 0:
        print("The x-coordinate is 0")
    case let p where p.1 == 0:
        print("The y-coordinate is 0")
    case let p where p.2 == 0:
        print("The z-coordinate is 0")
    default:
        print("No coordinate is 0")
}

# "The y-coordinate is 0"
let threeDimensionalPoint = (3, 0, 1)

switch (threeDimensionalPoint ) {
    case let (x, _, _) where x == 0:
        print("The x-coordinate is 0")
    case let (_, y, _) where y == 0:
        print("The y-coordinate is 0")
    case let (_, _, z) where z == 0:
        print("The z-coordinate is 0")
    default:
        print("No coordinate is 0")
}

# "The y-coordinate is 0"

# Instead of let (x, _, _), we could have used let (x, y, z), but I 
# chose not to because I was only checking a single coordinate
# in each where clause.

Have a look at (https://docs.swift.org/swift-book/documentation/the-swift-programming-language/controlflow/) . In particular, look at the examples in the sub-sections titled “Value Bindings” and “Where”.