使用协议将案例添加到现有枚举

时间:2015-12-01 16:52:57

标签: swift enums protocols

我想创建一个protocol,对符合此enums的所有protocol强制执行某个案例。

例如,如果我有enum这样的话:

enum Foo{
    case bar(baz: String)
    case baz(bar: String)
}

我想用protocol扩展它,增加另一个案例:

case Fuzz(Int)

这可能吗?

4 个答案:

答案 0 :(得分:31)

设计

解决方法是使用带有struct变量的static

注意:这是{strong> Swift 3 为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 CoolCar {

}

extension CoolCar {

    static var Yellow : Car {

        return Car(rawValue: "Yellow")
    }
}

extension Car : CoolCar {

}

调用

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")
}

注意:

请注意,此方法不能替代enum,只有在编译时不知道值时才使用此方法。

答案 1 :(得分:7)

不,因为您无法在case之外声明enum

答案 2 :(得分:6)

extension可以添加嵌套的enum,如下所示:

enum Plants {
  enum Fruit {
     case banana
  }
} 


extension Plants {
  enum Vegetables {
     case potato
  }
}

答案 3 :(得分:2)

以下是另外一些可能有助于那里的人:

使用您的示例:

enum Foo {
    case bar(baz: String)
    case baz(bar: String)
} 

你可以考虑&#34;筑巢&#34;它位于您自己case的{​​{1}}中:

enum

通过这种解决方案,访问隐藏的&#34;变得更加费力。案件相关类型。但是这种简化实际上在某些应用中可能是有益的。

另一种替代方法是,只需重新创建并扩展它,同时有办法将enum FooExtended { case foo(Foo) // <-- Here will live your instances of `Foo` case fuzz(Int) } 转换为扩展的Foo enum(例如,使用自定义FooExtended):< / p>

init

可能有很多地方这些解决方案中的一个,另一个或两个都没有任何意义,但我很确定它们可能对那里的某个人很方便(即使只是作为练习)。< / p>