【问题标题】:Define a specialised version of a protocol method定义协议方法的专用版本
【发布时间】:2021-07-13 09:53:06
【问题描述】:

我有一个具有如下关联类型的协议:

protocol Schedulable {
    associatedtype Phase

    var phase: Phase { get set }
    var duration: TimeInterval { get set }
}

我有另一个协议,它定义了一个泛型类型的方法,该泛型类型受限于之前的协议:

protocol Performed {
    func perform<S>(_ work: S) where S: Schedulable
}

现在假设我需要存储和检索往返于UserDefaults 的时间表。我需要任何符合Codable 协议的对象才能序列化其所有属性。特别是,我需要Schedulable 协议的关联类型符合Codable。顺便说一句,我不想​​把perform(_:)方法改成这样

func perform<S>(_ work: S) where S: Schedulable, S.Phase: Codable

我宁愿有另一种限制相位的方法。我考虑过使用可选的协议方法,但这些方法不适用于 Swift 结构。我怎样才能做到这一点?

【问题讨论】:

    标签: swift generics swift-protocols


    【解决方案1】:

    您可以使用不同的通用约束来定义重载,为什么不在协议中同时定义呢? 根据S.Phase 是否为Codable,将调用“更受约束”的方法。

    protocol Performed {
        func perform<S>(_ work: S) where S: Schedulable
        func perform<S>(_ work: S) where S: Schedulable, S.Phase: Codable
    }
    
    struct Runner: Performed {
        func perform<S>(_ work: S) where S: Schedulable {
            print("phase is not Codable!")
        }
        func perform<S>(_ work: S) where S: Schedulable, S.Phase: Codable {
            print("phase is Codable!")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      相关资源
      最近更新 更多