我有一个在 Controller 类中声明的 ApiRouter。我根据用户类型获取 JSON 对象。我想在声明时发送我的类型。例如;
api = ApiRouter.fetchJSON(.admin)
但它要我在 ApiRouter 类上声明它。 "
enum userType: String{
case admin = "Admin"
case user = "User"
}
enum ApiRouter: APIConfiguration {
case login(tckn:String, password:String)
case fetchJSON(type: userType)
case token
// MARK: - HTTPMethod
var method: HTTPMethod {
switch self {
case .login:
return .post
case .fetchJSON, .token:
return .get
}
}
// MARK: - Path
var path: String {
switch self {
case .login:
return "/login"
case .fetchJSON:
return "/profile/(\(userType)"
case .token:
return "/posts/"
}
}
最佳答案
您确定您不只是缺少参数名称吗?
api = ApiRouter.fetchJSON(type: .admin)
加上更新 ApiRouter 的路径属性:
// MARK: - Path
var path: String {
switch self {
case .login:
return "/login"
// you have to declare a variable to be able to use it:
case .fetchJSON(let type):
return "/profile/\(type)"
case .token:
return "/posts/"
}
}
如果你想在路径中使用rawValue
,那么使用:
case .fetchJSON(let type):
return "/profile/\(type.rawValue)"
测试使用:
enum userType: String{
case admin = "Admin"
case user = "User"
}
enum ApiRouter {
case login(tckn:String, password:String)
case fetchJSON(type: userType)
case token
// MARK: - HTTPMethod
var method: String {
switch self {
case .login:
return ""
case .fetchJSON, .token:
return ""
}
}
// MARK: - Path
var path: String {
switch self {
case .login:
return "/login"
case .fetchJSON(let type):
return "/profile/\(type.rawValue)"
case .token:
return "/posts/"
}
}
}
let api = ApiRouter.fetchJSON(type: .admin)
print(">> \(api.path)")
已打印:>>/profile/Admin
关于ios - 不初始化引用枚举类型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48318894/