有没有办法使函数接受任何具有String的rawValue的枚举类型? [英] Is there a way to make a function to accept any Enum types that have a rawValue of String?

查看:149
本文介绍了有没有办法使函数接受任何具有String的rawValue的枚举类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 协议StringRepresentable 
{
var rawValue:String {get}
}

struct Endpoint
{
枚举用户:String,StringRepresentable
{
case Login =/ user / login
case Register =/ user / register
}

枚举项:String,StringRepresentable
{
case Like =/ item / like
case Buy =/ item / buy
}
}

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

let userLoginEndpoint = urlString(Endpoint.User 。登录)
let buyItemEndpoint = urlString(Endpoint.Item.Buy)

有没有比其他方式好吗?



还是有一个协议,已经提供了这样的东西,我错过了?

解决方案

已经有 RawRepresentable 协议,可以做你想要的。



你可以扩展基于 RawValue == String


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?

解决方案

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

And you can extend based on whether RawValue == String

这篇关于有没有办法使函数接受任何具有String的rawValue的枚举类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆