有没有办法让函数接受任何具有 rawValue 字符串的枚举类型?
Is there a way to make a function to accept any Enum types that have a rawValue of String?
我想到的一种方法是制定一个其他 Enum 必须遵守的协议。
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)
还有比这更好的方法吗?
或者是否有我错过的协议,已经提供了类似的东西?
已经有 RawRepresentable
协议可以满足您的需求。
并且可以根据是否RawValue == String
进行扩展
我想到的一种方法是制定一个其他 Enum 必须遵守的协议。
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)
还有比这更好的方法吗?
或者是否有我错过的协议,已经提供了类似的东西?
已经有 RawRepresentable
协议可以满足您的需求。
并且可以根据是否RawValue == String