Swift 3, switch statement, case hasPrefix

In Swift2, you might have something similar to the following code:

switch productIdentifier { case hasSuffix("q"): return "Quarterly".localized case hasSuffix("m"): return "Monthly".localized default: return "Yearly".localized } 

and it will work. In Swift 3, the only way I can do the above is:

  switch productIdentifier { case let x where x.hasSuffix("q"): return "Quarterly".localized case let x where x.hasSuffix("m"): return "Monthly".localized default: return "Yearly".localized } 

which seems to be losing the clarity of the Swift2 version, and it makes me think that I was missing something. The above version is, of course, simple. I'm curious if anyone has a better way to handle this?

+5
source share
2 answers

I donโ€™t know if this is better than using value binding, as in your example, but you can just use underscore,

 switch productIdentifier { case _ where productIdentifier.hasSuffix("q"): return "Quarterly".localized case _ where productIdentifier.hasSuffix("m"): return "Monthly".localized default: return "Yearly".localized 
+5
source

It seems you are only checking the last character of the productIdentifier. You can do it as follows:

 switch productIdentifier.characters.last { case "q"?: return "Quarterly".localized case "m"?: return "Monthly".localized default: return "Yearly".localized } 
+3
source

Source: https://habr.com/ru/post/1258651/


All Articles