使用协议将案例添加到现有枚举 [英] Adding a case to an existing enum with a protocol
本文介绍了使用协议将案例添加到现有枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个协议
,该协议对所有符合此<$ c $的枚举 c强制执行某种情况c>协议
。
I want to create a protocol
that enforces a certain case on all enums
conforming to this protocol
.
例如,如果我有枚举
,例如:
For example, if I have a enum
like this:
enum Foo{
case bar(baz: String)
case baz(bar: String)
}
我想用协议
扩展它,并增加另一种情况:
I want to extend it with a protocol
that adds another case:
case Fuzz(Int)
这可能吗?
推荐答案
设计
解决方法是将 struct
与 static
变量一起使用。
注意:这是在 Swift 3 中完成的,用于 Notification.Name
Note: This is what is done in Swift 3 for Notification.Name
以下是 Swift 3
struct Car : RawRepresentable, Equatable, Hashable, Comparable {
typealias RawValue = String
var rawValue: String
static let Red = Car(rawValue: "Red")
static let Blue = Car(rawValue: "Blue")
//MARK: Hashable
var hashValue: Int {
return rawValue.hashValue
}
//MARK: Comparable
public static func <(lhs: Car, rhs: Car) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
协议
Protocol
protocol CoolCar {
}
extension CoolCar {
static var Yellow : Car {
return Car(rawValue: "Yellow")
}
}
extension Car : CoolCar {
}
调用
Invoking
let c1 = Car.Red
switch c1 {
case Car.Red:
print("Car is red")
case Car.Blue:
print("Car is blue")
case Car.Yellow:
print("Car is yellow")
default:
print("Car is some other color")
}
if c1 == Car.Red {
print("Equal")
}
if Car.Red > Car.Blue {
print("Red is greater than Blue")
}
< h1>注意:
请注意,该方法不能代替枚举
,仅当值为在编译时未知。
Note:
Please note this approach is not a substitute for enum
, use this only when the values are not known at compile time.
这篇关于使用协议将案例添加到现有枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文