cfi*_*her 18 enums protocols swift
我想创建一个protocol强制执行某个案例的所有enums符合此要求的案例protocol.
例如,如果我有enum这样的:
enum Foo{
case bar(baz: String)
case baz(bar: String)
}
Run Code Online (Sandbox Code Playgroud)
我想扩展它protocol,增加另一个案例:
case Fuzz(Int)
Run Code Online (Sandbox Code Playgroud)
这可能吗?
use*_*037 36
解决方法是使用struct带static变量的变量.
注意:这是在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
}
}
Run Code Online (Sandbox Code Playgroud)
protocol CoolCar {
}
extension CoolCar {
static var Yellow : Car {
return Car(rawValue: "Yellow")
}
}
extension Car : CoolCar {
}
Run Code Online (Sandbox Code Playgroud)
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")
}
Run Code Online (Sandbox Code Playgroud)
请注意,此方法不能替代enum,只有在编译时未知值时才使用此方法.
小智 6
一个extension可以添加嵌套enum,就像这样:
enum Plants {
enum Fruit {
case banana
}
}
extension Plants {
enum Vegetables {
case potato
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10612 次 |
| 最近记录: |