Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift enum associated values

Tags:

enums

swift

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
like image 218
Evgeniy Kleban Avatar asked Dec 23 '22 14:12

Evgeniy Kleban


2 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

like image 98
totiDev Avatar answered Jan 04 '23 23:01

totiDev


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)"
    }
}
like image 41
David Pilkington Avatar answered Jan 04 '23 21:01

David Pilkington