Swift 3,switch语句,case hasPrefix

Ale*_*exK 5 switch-statement swift3

在Swift2中,您可以使用类似于以下代码的内容:

    switch productIdentifier {
    case hasSuffix("q"):
        return "Quarterly".localized
    case hasSuffix("m"):
        return "Monthly".localized
    default:
        return "Yearly".localized
    }
Run Code Online (Sandbox Code Playgroud)

它会起作用.在Swift 3中,我能完成上述工作的唯一方法是:

    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
    }
Run Code Online (Sandbox Code Playgroud)

这似乎失去了Swift2版本的清晰度 - 它让我觉得我错过了一些东西.以上是一个简单的版本.我很好奇是否有人有更好的处理方式?

rde*_*mar 11

我不知道这是否比在您的示例中使用值绑定更好,但您可以只使用下划线,

switch productIdentifier {
case _ where productIdentifier.hasSuffix("q"):
    return "Quarterly".localized
case _ where productIdentifier.hasSuffix("m"):
    return "Monthly".localized
default:
    return "Yearly".localized
Run Code Online (Sandbox Code Playgroud)