ios - 不初始化引用枚举类型对象

标签 ios swift enums swift4

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

Error

最佳答案

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

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/

相关文章:

ios - 如何使用纬度和经度获取加码

ios - 缩放 UIViews 组但保持其位置

ios - iOS 应用程序的版本号和内部版本号可以是字符串吗?

swift - 通用可选枚举函数

ios - show() View Controller 不起作用

ios - 使用公共(public) IP 绑定(bind)套接字,以便可以使用 telnet 访问

ios - iMessage 中的导航栏高度 (iOS 10)

ios - 如何快速返回 UIView View 及其 subview ?

java - 在 Eclipse 中将 Java Enums 和 ArrayList 与 JAX-WS 结合使用

java - 使用 java reflect 找出两个类是否属于同一类型(类、接口(interface)、枚举等)