首页 > 解决方案 > 如何获取枚举中的参数名称?

问题描述

我的代码是这样的:</p>

enum API {
    case login(phone:String, password:String, deviceID:String)
}

extension API:TargetType {
    var task: Task {
        switch self {
        case let .login(phone, password, deviceID):
            ///How to get the parameter name here?
            ///For example:"phone", "password", "deviceID"
            ///Can this be generated automatically?
            let parameters = 
                ["phone":phone,
                 "password:":password,
                 "deviceID":deviceID]
            return .requestParameters(parameters, encoding: JSONEncoding.default);
        }
    }
}

如何获取 Switch case 中的参数名称?例如:“phone”、“password”、“deviceID” 这个可以自动生成吗?

如何避免从字面上写“电话”和其他字典键,并使编译器从关联的值标签生成它们。

也许完成后是这样的

func parameters(_ api:API) -> [String, Any] {

}

switch self {
case .login:
    return .requestParameters(parameters(self), encoding: JSONEncoding.default);
}

似乎暂时无法完成。

谁是主角?</p>

标签: swiftenums

解决方案


您可以将枚举案例的所有关联值分配给单个变量,然后使用它们的标签访问单独的值。

enum API {
    case login(phone:String, password:String, deviceID:String)
}

extension API:TargetType {
    var task: Task {
        switch self {
        case let .token(params)
            let parameters = 
                ["phone":params.phone,
                 "password:":params.password,
                 "deviceID":params.deviceID]
            return .requestParameters(parameters, encoding: JSONEncoding.default);
        }
    }
}

顺便说一句,那不.token应该.login吗?您定义的没有.token案例。API enum

如果要生成Dictionary键以匹配String关联值标签的表示,这无法自动完成,但作为一种解决方法,您可以定义另一个具有String原始值的枚举并将其用于Dictionary键。

enum API {
    case login(phone:String, password:String, deviceID:String)

    enum ParameterNames: String {
        case phone, password, deviceID
    }
}

extension API:TargetType {
    var task: Task {
        switch self {
        case let .token(params)
            let parameters = 
                ["\(API.ParameterNames.phone)" : params.phone,
                 "\(API.ParameterNames.phone)" : params.password,
                 "\(API.ParameterNames.deviceID)" : params.deviceID]
            return .requestParameters(parameters, encoding: JSONEncoding.default);
        }
    }
}

推荐阅读