快速连接嵌套枚举字符串 [英] concatenate nested enum string in swift
问题描述
我想声明一个枚举类型(例如ParentEnum),它将用作函数的参数,它包含多个子枚举,并且每个子枚举的情况都使用子枚举的名称作为前缀,例如:
I want to declare an enum type (say, ParentEnum) which will be used as an argument of a function, it contains a number of "child" enums and each case of the child enum uses the name of the child enum as a prefix, here's an example:
enum ParentEnum: String {
enum ChildEnum1: String {
case c1 = "/ChildEnum1/c1"
case c2 = "/ChildEnum1/c2"
}
enum ChildEnum2: String {
case c1 = "/ChildEnum2/c1"
case c2 = "/ChildEnum2/c2"
}
...
}
有没有一种方法可以概括 / ChildEnumX部分,因此我只需要将 / cX定义为其rawValue,当我调用 ParentEnum.ChildEnumX.c1
,它将像上面的示例一样为我提供 / ChildEnumX / c1。
Is there a way to generalize the "/ChildEnumX" part so I only need to define "/cX" as its rawValue, and when I call ParentEnum.ChildEnumX.c1
, it will give me "/ChildEnumX/c1" like the example above.
我希望这样做有意义,在此先感谢。
I hope this makes sense, thanks in advance.
推荐答案
记得要更新此帖子,以防其他人遇到相同的问题,这是w我想出的帽子是
Just remembered to update this post in case someone else has the same problem, this is what I came up with:
enum ParentEnum {
case Child1(ChildEnum1)
case Child2(ChildEnum2)
enum ChildEnum1: String {
case c1 = "/c1"
case c2 = "/..."
}
enum ChildEnum2: String {
case c1 = "/..."
case c2 = "/..."
}
...
var rawValue: String {
switch self {
case .Child1(let child):
return "ChildEnum1/\(child.rawValue)"
case .Child2(let child):
return "ChildEnum2/\(child.rawValue)"
}
}
}
如果将ParentEnum用作函数的参数,则 .Child1(.c1).rawValue
会产生 ChildEnum1 / c1
。您还可以覆盖Child枚举的 rawValue
以进一步扩展嵌套级别。希望这会有所帮助。
if you were using ParentEnum as an argument of a function, .Child1(.c1).rawValue
would yield "ChildEnum1/c1"
. You could also override the rawValue
of the Child enums to further extend the nesting levels. Hope this helps.
这篇关于快速连接嵌套枚举字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!