In Swift2, you could 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 would work. In Swift 3, the only way I can make the above work 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 lose the clarity of the Swift2 version - and it makes me think I'm missing something. The above is a simple version of course. I'm curious if anyone has a better way of handling that?
In the most basic form of a switch/case you tell Swift what variable you want to check, then provide a list of possible cases for that variable. Swift will find the first case that matches your variable, then run its block of code. When that block finishes, Swift exits the whole switch/case block.
Switch Statement: where Clause - Learn Swift | Codecademy. Another neat feature available for the cases of a switch statement is the where clause. The where clause allows for additional pattern matching for a given expression. It can also be used with loops and other conditionals such as if statements.
In a switch statement, we pass a variable holding a value in the statement. If the condition is matching to the value, the code under the condition is executed. The condition is represented by a keyword case, followed by the value which can be a character or an integer.
The switch statement in Swift lets you inspect a value and match it with a number of cases. It's particularly effective for taking concise decisions based on one variable that can contain a number of possible values. Using the switch statement often results in more concise code that's easier to read.
I don't know if this is any better than using value binding as in your example, but you can just use an underscore instead,
switch productIdentifier {
case _ where productIdentifier.hasSuffix("q"):
return "Quarterly".localized
case _ where productIdentifier.hasSuffix("m"):
return "Monthly".localized
default:
return "Yearly".localized
You seem to be only checking the last character of the productIdentifier
. You could do it this way:
switch productIdentifier.last {
case "q"?:
return "Quarterly".localized
case "m"?:
return "Monthly".localized
default:
return "Yearly".localized
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With