Mr Some Dev.
Mr Some Dev.

Reputation: 315

Refer to enum type object without initialize

I have an ApiRouter which I declare in the controller class. I fetch a JSON object depends on user type. I want to send my type when I declare it. For example;

api = ApiRouter.fetchJSON(.admin)

but It wants me to declare it on ApiRouter class. "

 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

Upvotes: 0

Views: 126

Answers (2)

Milan Nosáľ
Milan Nosáľ

Reputation: 19737

Are you sure you are not just missing the parameter name?

api = ApiRouter.fetchJSON(type: .admin)

Plus update the path property of the 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/"
    }
}

If you want to use the rawValue in path, then use:

case .fetchJSON(let type):
    return "/profile/\(type.rawValue)"

Tested using:

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)")

Printed: >> /profile/Admin

Upvotes: 1

Sarabjit Singh
Sarabjit Singh

Reputation: 1824

Please initialize your userType like following :

    var userTypeObj : userType = . User

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

Upvotes: 0

Related Questions