Is there a way to make a function to accept any Enum types that have a rawValue of String?

Deadly 提交于 2019-12-10 23:34:37

问题


One way I came up with is to make a protocol that other Enum must conform to.

protocol StringRepresentable
{
    var rawValue: String { get }
}

struct Endpoint
{
    enum User: String, StringRepresentable
    {
        case Login = "/user/login"
        case Register = "/user/register"
    }

    enum Item: String, StringRepresentable
    {
        case Like = "/item/like"
        case Buy = "/item/buy"
    }
}

func urlString(endpoint: StringRepresentable) -> String
{
    return "http://www.example.com\(endpoint.rawValue)"
}

let userLoginEndpoint = urlString(Endpoint.User.Login)
let buyItemEndpoint = urlString(Endpoint.Item.Buy)

Is there any other way that better than this?

Or is there a protocol, already provided something like this, that I missed?


回答1:


There is already the RawRepresentable protocol which does what you want.

And you can extend based on whether RawValue == String



来源:https://stackoverflow.com/questions/32946576/is-there-a-way-to-make-a-function-to-accept-any-enum-types-that-have-a-rawvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!