我的代码是这样的:
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);
}
看来暂时无法完成。
谁是英雄?
最佳答案
您可以将枚举案例的所有关联值分配给单个变量,然后使用它们的标签访问单独的值。
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
吗?您的 API
enum
中没有定义 .token
大小写。
如果你想生成 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);
}
}
}
关于swift - 如何获取枚举中的参数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53847717/