What is meaning of "where" keyword?

ios, swift

Solution

The `where` in that context is used as pattern matching. From the example:

case let x where x.hasSuffix("pepper"):

When the suffix of `x` matches `"pepper"` it will set the constant `vegetableComment`:

let vegetableComment = "Is it a spicy \(x)?"

You can see as well that `x` can´t be "celery", "cucumber" or "watercress", otherwise it would give you a different outcome:

case "celery":
    let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
    let vegetableComment = "That would make a good tea sandwich."

Because those cases are before `case let x where x.hasSuffix("pepper"):`. You can try changing the order of them and pass the value "celery" to see a different outcome.

Edit:

From my understanding it creates a constant `x` if `x`'s suffix is "pepper". The goal of creating this constant, is for you to use it after that:

let vegetableComment = "Is it a spicy \(x)?"

Edit 2:

After a bit more research, that's called value binding and it's described as:

switch case can bind the value or values it matches to temporary constants or variables, for use in the body of the case. This is known as value binding, because the values are “bound” to temporary constants or variables within the case’s body.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/gb/jEUH0.l

Problem

I couldn't understand exact meaning of this statement. ``` let x where x.hasSuffix("pepper") ``` What is meaning of that? Note: There is no need of `let` use? It makes me confusing.. Is this enough `x where x.hasSuffix("pepper")`? because, `let x` should be already get assigned.? Update: From @Jacky comment here, it could be meaning same as below. ``` let x = vegetable if (x.hasSuffix("pepper") ...... ```

Original source

Related problems