AlexK
AlexK

Reputation: 638

Swift 3, switch statement, case hasPrefix

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?

Upvotes: 8

Views: 4510

Answers (2)

vacawama
vacawama

Reputation: 154691

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
}

Upvotes: 3

rdelmar
rdelmar

Reputation: 104092

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

Upvotes: 24

Related Questions