简体   繁体   中英

Define a specialised version of a protocol method

I have a protocol with an associated type like the following:

protocol Schedulable {
    associatedtype Phase

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

I have another protocol which defines a method on a generic type constrained to the previous protocol:

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

Let's now suppose I need to store and retrieve a schedule to and from the UserDefaults . I need any object to conform to the Codable protocol in order to serialize all its properties. In particular, I need the associated type of the Schedulable protocol to conform to Codable . By the way, I do not want to change the perform(_:) method to be like

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

I would rather have another method which constrains the phase. I thought about using the optional protocol methods, but those do not work with Swift structs. How can I achieve this?

You can define overloads with different generic constraints, why not just define both in the protocol? Depending on if S.Phase is Codable or not, the "more constrained" method will be called.

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!")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM