问题
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