How does let x where x.hasSuffix(“pepper”) work

后端 未结 2 1875
伪装坚强ぢ
伪装坚强ぢ 2021-02-14 16:50

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

let vegetable = \"red pepper\"

switch vegetable {
          


        
相关标签:
2条回答
  • 2021-02-14 17:24

    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.

    0 讨论(0)
  • 2021-02-14 17:28

    There is actually no reason to use let x in this scenario. case let x where x.hasSuffix("pepper"): can simply be replaced with case vegetable where vegetable.hasSuffix("pepper"). In this scenario, an extra variable x is declared which copies vegetable. This is useless, and arguable reduces readability, even if you renamed x to vegetable as well.

    Using let in a switch statement case is useful in other cases, such as when the "argument" (vegetable) is not a variable, e.g. switch(getVegetableName()) , or in the case where the "argument" is a tuple, and needs to be unpacked, such as in

    let vegetableNameAndCountry = ("Sweet Potato", "United States")
    
    switch(vegetableNameAndCountry) {
       case (let vegetable, let country) where country == "Tanzania":
           print("This \(vegetable) comes from a country north of Kenya")
       case ("Sweet Potato", _): // Note here I ignore the country, and don't even bother creating a constant for it
           print("Sweet sweet potatoes")
       default:
           print("We don't care about this vegetable")
    }
    
    0 讨论(0)
提交回复
热议问题