簡體   English   中英

Swift枚舉關聯值

[英]Swift enum associated values

我的API有路徑和后面的int。

例如, /get/news/{id}.

對於路徑端點,我有這樣的枚舉:

enum Endpoints : String {

case news = "news"
}

有沒有方便的方法來使用相關的值?

就像是 :

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

你可以用這個:

enum APIEndpoints {
    case news(id: Int)

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

並使用它: APIEndpoints.news(id: 5).path

您始終可以向枚舉添加函數以獲取URI:

enum Endpoints : String {
    case news = "news"

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

你可以試試這個:

enum Endpoints: String {
   case news

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM