首页 > 解决方案 > 在swift中以默认情况访问switch case参数

问题描述

我有一个 URLRequestConvertible 枚举(AlamoFire),带有案例

getId(String), getList(String, String), getFullList(String, String) 等等。

在里面

public func asURLRequest() throws -> URLRequest {

方法,我需要访问所有情况下通用的第一个参数。我想知道它是否可以在默认情况下访问,或者有没有办法以通用方式提及所有情况。像元组中的变量。

现在我正在访问这样的论点

var headerValue : String {

    switch self {

    case .getId(let value):
        return value
    case .getList(let value, _):
        return value
    case .getFullList(let value, _):
        return value
    }
}

我期待类似的东西

case let check(let value, _): return value 

欢迎任何关于我如何从这里处理它的建议

标签: swiftswitch-statementalamofire

解决方案


您至少可以将其稍微简化为

var headerValue : String {
    switch self {
    case .getId(let value),
         .getList(let value, _),
         .getFullList(let value, _):
        return value
    }
}

因为所有情况都将相同的变量绑定到相同的类型。


推荐阅读