swift 经典代码收集 和 赏析

代码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 = 0 while let item = Self(rawValue: value) { result.append(item) value += 1 } return result }
  //这个方法巧妙运用了函数式编程,通过id,在allValues数组中查询一个实现了此协议的对象
static func fromPermanentID(id: String) -> Self? { return allValues.indexOf { $0.permanentID == id }.flatMap { self.init(rawValue: $0) } } }


原文地址:https://www.cnblogs.com/xuezizhenchengxuyuan/p/5649810.html