Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does let x where x.hasSuffix("pepper") work

In the code block below, I am having trouble understanding let x where x.hasSuffix("pepper").

let vegetable = "red pepper"

switch vegetable {
    case "celery":
        let vegetableComment = "Add some raisins and make ants on a log."
    case "cucumber", "watercress":
        let vegetableComment = "That would make a good tea sandwhich"
    case let x where x.hasSuffix("pepper"):
        let vegetableComment = "Is it a spicy \(x)"
    default:
        let vegetableComment = "Everything tastes good in soup."
}

Console output

vegetableComment: Is it a spicy red pepper

It seems like the following logic is happening.

x = vegetable
if (x's suffix == 'pepper') 
    run case

Can someone explain this better for me?

like image 388
Arian Faurtosh Avatar asked Jun 02 '14 22:06

Arian Faurtosh


1 Answers

vegetable is an implicit String. It's the same as you would write:

var vegetable: String = "red pepper"

hasSuffix is declared as func hasSuffix(suffix: String) -> Bool an therefore returns a Bool. The where keyword specifies additional requirements, and can only be used in switch statements.
Because all of this is suffused, the vegetable variable is assigned to x (let x).

You can read more about the where and switch here.

like image 177
Leandros Avatar answered Nov 07 '22 16:11

Leandros