Swift enum associated values

Viewed 485

I have API that have path and an int after it.

For example, /get/news/{id}.

For path endpoints i have enum like that:

enum Endpoints : String {

case news = "news"
}

Is there any convinient way to use associated values with it?

Something like :

case newsById(id: String) = "get/news/" + id
3 Answers

You can use this:

enum APIEndpoints {
    case news(id: Int)

    var path: String {
        switch self {
        case let .news(id):
            return "/get/news/\(id)"
        }
    }
}

And use it like: APIEndpoints.news(id: 5).path

You can always add a function to the enum to get the URI:

enum Endpoints : String {
    case news = "news"

    func getUri(id: string) -> String {
        return "get/\(self.rawValue)/\(id)"
    }
}

you could try this:

enum Endpoints: String {
   case news

   func getNewsByStringId() -> String {
     return "get/news/\(self.rawValue)"
   }
}
Related