swift - 如何获取枚举中的参数名称?
问题描述
我的代码是这样的:</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>
解决方案
您可以将枚举案例的所有关联值分配给单个变量,然后使用它们的标签访问单独的值。
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);
}
}
}
推荐阅读
- python - Python:根据匹配从列表中写入文件
- angular - 如何在 Angular 中正确配置路由
- excel - 交互式 Excel 图表:根据下拉选择获取多列的值
- ubuntu - AWS Ubuntu:从 Snap Store 配置 Ejabberd 主机
- python-3.x - TypeError: 'int' object is not iterable 这是一个在 6 位密码中计算不同数量结果的程序
- node.js - 使用 node-cron 进行调度部署 Discord.js 机器人时的端口绑定时间问题
- javascript - 如何添加新脚本并将其加载到滚动条上?
- c++ - 减少类中的模板混乱
- css - CSS 动画比例变换在 Firefox 中开始模糊
- merge - Gulp 4 ReferenceError:未定义合并