swift 经典代码收集 和 赏析

时间:2022-06-01 21:30:11
代码1:
protocol PickableEnum
{
var displayName: String { get }
var permanentID: String { get }
static var allValues: [Self] { get }
static func fromPermanentID(id: String) -> Self?
} //下面的扩展表面了这个协议的实例必须实现了RawRepresentable协议,并且字面值必须是Int类型
extension PickableEnum where Self: RawRepresentable, Self.RawValue == Int
{
var displayName: String
{
return Localised("\(self.dynamicType).\(self)")
} var permanentID: String
{
return String(self)
} static var allValues: [Self]
{
var result: [Self] = []
var value =
while let item = Self(rawValue: value)
{
result.append(item)
value +=
}
return result
}

  //这个方法巧妙运用了函数式编程,通过id,在allValues数组中查询一个实现了此协议的对象
static func fromPermanentID(id: String) -> Self?
{
return allValues.indexOf { $.permanentID == id }.flatMap { self.init(rawValue: $) }
}
}