【问题标题】:Refer to enum type object without initialize引用枚举类型对象而不进行初始化
【发布时间】:2018-01-18 10:19:40
【问题描述】:

我有一个在控制器类中声明的 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/"
    }
}

【问题讨论】:

  • enum ApiRouter 没有右大括号
  • 尝试将 return "/profile/((userType)" 替换为 return "/profile/((userType.rawValue)"
  • 立即查看我的答案

标签: ios swift enums swift4


【解决方案1】:

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

api = ApiRouter.fetchJSON(type: .admin)

另外更新ApiRouter的path属性:

// 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

【讨论】:

    【解决方案2】:

    请像下面这样初始化你的用户类型:

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

    【讨论】:

    • 我的问题是我无法在没有初始化路由器类的情况下编译它。你的回答并没有解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    • 2011-10-21
    • 1970-01-01
    相关资源
    最近更新 更多