扩展协议属性以在Swift中提供默认实现

时间:2018-09-22 18:59:02

标签: swift protocols

我有一个用于多个枚举的协议,其中包括Swift 4.2的CaseIterable

    public protocol CycleValue: CaseIterable {

  /// Computed property that returns the next value of the property.
  var nextValue:Self { get }
}

我的CycleValue用例之一是带有Theme属性:

@objc public enum AppThemeAttributes: CycleValue  {

  case classic, darkMode // etc.

  public var nextValue: AppThemeAttributes {
    guard self != AppThemeAttributes.allCases.last else {
      return AppThemeAttributes.allCases.first!
    }

    return AppThemeAttributes(rawValue: self.rawValue + 1)!
  }
}

我还有其他用例;例如按钮类型。 CaseIterable简化了nextValue的实现,但是对于所有类型的CycleValue都是相同的。

我想实现CycleValue的扩展,该扩展为nextValue属性提供默认实现,并避免重复代码(即:DRY!)。

我一直在与PAT(协议相关类型)作斗争。似乎语法不正确。

应该有可能吧?我如何为nextValue提供默认实现以避免ode重复?

1 个答案:

答案 0 :(得分:6)

一种可能的解决方案是在allCases集合中找到当前值, 并返回下一个元素(或环绕到第一个元素):

public protocol CycleValue: CaseIterable, Equatable {
    var nextValue: Self { get }
}

public extension CycleValue {
    var nextValue: Self {
        var idx = Self.allCases.index(of: self)!
        Self.allCases.formIndex(after: &idx)
        return idx == Self.allCases.endIndex ? Self.allCases.first! : Self.allCases[idx]
    }
}

(请注意,两个强制拆包都是安全的!) 示例:

public enum AppThemeAttributes: CycleValue  {
    case classic, darkMode // etc.
}

let a = AppThemeAttributes.classic
print(a) // classic
let b = a.nextValue
print(b) // darkMode
let c = b.nextValue
print(c) // classic

协议必须符合Equatable才能进行编译,但是 不是真正的限制:CaseIterable协议不能具有 关联的值,以便编译器始终可以合成 Equatable符合性。

相关问题