Ios 在不初始化的情况下引用枚举类型对象
我在控制器类中声明了一个ApiRouter。获取JSON对象取决于用户类型。我想在声明时发送我的类型。比如, api=ApiRouter.fetchJSON(.admin) 但它要我在ApiRouter类上声明它。"Ios 在不初始化的情况下引用枚举类型对象,ios,swift,enums,swift4,Ios,Swift,Enums,Swift4,我在控制器类中声明了一个ApiRouter。获取JSON对象取决于用户类型。我想在声明时发送我的类型。比如, api=ApiRouter.fetchJSON(.admin) 但它要我在ApiRouter类上声明它。" 请按如下方式初始化您的用户类型: var userTypeObj : userType = . User api = ApiRouter.fetchJSON(type: userTypeObj.User) 是否确实没有丢失参数名称 api = ApiRouter.fet
请按如下方式初始化您的用户类型:
var userTypeObj : userType = . User
api = ApiRouter.fetchJSON(type: userTypeObj.User)
是否确实没有丢失参数名称
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
枚举ApiRouter不关闭括号替换return“/profile/((userType)”为return“/profile/((userType.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)")