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

后端 未结 2 1885
伪装坚强ぢ
伪装坚强ぢ 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: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")
    }
    

提交回复
热议问题