使用枚举来过滤后续枚举中的选项作为函数参数

时间:2018-12-29 18:50:04

标签: swift enums

我想使用2个枚举来控制使用以下客户端时可用的选项。

基本上,如果APIService.identity,则APIEndpoints应该只返回该服务上的端点。在这种情况下,.accessToken

我什至不确定这是否可行,但是,我怎么能做到这一点呢?

import UIKit

struct MyModel: Codable {
    let id: String
}

enum Result<T> {
    case success(T)
    case error(String)
}

protocol ServiceType {}

protocol EndpointType {
    var baseURL: String { get }
    var path: String { get }
}

// MARK: - APIEndpoints

enum APIEndpoints {
    // MARK: - Profile

    case userProfile(userId: String)

    // MARK: - Identity

    case accessToken(company: String, code: String)
}

extension APIEndpoints: EndpointType {
    var baseURL: String {
        switch self {
        case .userProfile:
            return "https://profile.foo.bar"
        case .accessToken:
            return "https://identity.foo.bar"
        }
    }

    var path: String {
        switch self {
        case .userProfile(let userId):
            return "/profile/\(userId)/something"
        case .accessToken(let props):
            return "/auth/realms/\(props.company)/protocol/openid-connect/token"
        }
    }
}

// MARK: - APIService

enum APIService {
    case profile
    case identity
}

extension APIService: ServiceType {}

// MARK: - Client

protocol ClientType {
    func request(forService service: APIService, onEndpoint endpoint: APIEndpoints, completion: @escaping (Result<MyModel>) -> Void)
}

class Client: ClientType {
    func request(forService service: APIService, onEndpoint endpoint: APIEndpoints, completion: @escaping (Result<MyModel>) -> Void) {
        let responseResult = Bool.random()
        if responseResult {
            guard let data = "{\"id\":\"1234\"}".data(using: .utf8), let value = try? JSONDecoder().decode(MyModel.self, from: data) else { return completion(.error("Decoder Error")) }
            completion(.success(value))
        } else {
            completion(.error("Foo"))
        }
    }
}

let client = Client()

client.request(forService: .identity, onEndpoint: .accessToken(company: "foobar", code: "123")) { response in
    switch response {
    case .success(let values):
        print("do something with \(values.id)")
    case .error(let error):
        print("do something with an error of type \(error)")
    }
}

0 个答案:

没有答案
相关问题