请参阅枚举类型对象而不初始化

时间:2018-01-18 10:19:41

标签: ios swift enums swift4

我有一个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/"
    }
}

Error

2 个答案:

答案 0 :(得分:1)

您确定不只是缺少参数名称吗?

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

答案 1 :(得分:0)

请初始化您的userType,如下所示:

    var userTypeObj : userType = . User

api = ApiRouter.fetchJSON(type: userTypeObj.User)