How to resolve x, where x.hasSuffix ("pepper") works

In the code block below, there is a problem 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 exit

vegetableComment: Is it spicy red pepper

It seems that the following logic is happening.

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

Can someone explain this better for me?

+8
swift swift-playground
source share
1 answer

vegetable is an implicit String . This is the same thing you write:

 var vegetable: String = "red pepper" 

hasSuffix declared as func hasSuffix(suffix: String) -> Bool , therefore returns a Bool . The where keyword defines additional requirements and can only be used in switch .

Since all this is full, the variable vegetable assigned the value x ( let x ).

Read more about where and switch here .

+17
source share

All Articles