对于具有关联值的枚举,Swift 不提供相等运算符。所以我实现了一个能够比较两个枚举:
enum ExampleEnum{
case Case1
case Case2(Int)
case Case3(String)
...
}
func ==(lhs: ExampleEnum, rhs: ExampleEnum) -> Bool {
switch(lhs, rhs){
case (.Case1, .Case1): return true
case let (.Case2(l), .Case2(r)): return l == r
case let (.Case3(l), .Case3(r)): return l == r
...
default: return false
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我有很多这样的枚举,有很多案例,所以我需要写很多这样的比较代码(对于每个枚举,对于每个案例)。
如您所见,这段代码始终遵循相同的方案,因此似乎有一种更抽象的方式来实现比较行为。有没有办法解决这个问题?例如泛型?
我有以下xml数据结构进行转换:
<root>
<main1>
<text-body>
<title>A</title>
<subtitle>A</subtitle>
</text-body>
<!-- other stuff -->
<text-body>
<titel>Aa</titel>
<subtitel>Aa</subtitel>
</text-body>
<!-- other stuff -->
<text-body>
<titel>Aaa</titel>
<subtitel>Aaa</subtitel>
</text-body>
</main1>
<main2>
<text-body>
<title>B</title>
<subtitle>B</subtitle>
<body>B</body>
</text-body>
<text-body>
<title>C</title>
<subtitle>C</subtitle>
<body>C</body>
</text-body>
<text-body>
<title>D</title>
<subtitle>D</subtitle>
<body>D</body>
</text-body>
</main2>
</root>
Run Code Online (Sandbox Code Playgroud)
我需要将main/text-body中的数据替换为main2/text-body中的数据,但保留main1中的其他内容.输出应如下所示:
<root>
<main1>
<text-body>
<title>B</title>
<subtitle>B</subtitle>
<body>B</body>
</text-body>
<!-- other stuff -->
<text-body>
<title>C</title>
<subtitle>C</subtitle>
<body>C</body>
</text-body>
<!-- other stuff -->
<text-body>
<title>D</title>
<subtitle>D</subtitle>
<body>D</body>
</text-body>
</main1>
<main2>
<text-body>
<title>B</title>
<subtitle>B</subtitle>
<body>B</body>
</text-body>
<text-body>
<title>C</title>
<subtitle>C</subtitle>
<body>C</body>
</text-body> …Run Code Online (Sandbox Code Playgroud)