I have a Savable protocol that has multiple versions of save() method based on the conformance of C1 and C2. And then there is another Downloadable protocol that conforms to Savable protocol that calls the Savable's save() method based on the conformance of C1 and C2.
As can be seen from the sample code below, the download() methods are all the same. Is there a way to simplify this code by removing the repetitive functions? Or should I use another totally different approach to get the same outcome?
PS: Both Savable and Downloadable need to be a protocol for some unmentioned technical reasons. Furthermore, C1 and C2 both have Self or associated type requirements, thus performing a type check is not possible.
// Constraint
protocol C1 { }
protocol C2 { }
// Savable
protocol Savable { }
extension Savable {
func save() {
print("Perform basic save")
}
}
extension Savable where Self: C1 {
func save() {
print("Perform save C1")
}
}
extension Savable where Self: C1 & C2 {
func save() {
print("Perform save C1 & C2")
}
}
// Downloadable
protocol Downloadable: Savable { }
extension Downloadable {
func download() {
print("Perform download")
save()
}
}
extension Downloadable where Self: C1 {
func download() {
print("Perform download")
save()
}
}
extension Downloadable where Self: C1 & C2 {
func download() {
print("Perform download")
save()
}
}
// Usage
class MyClassC1: Downloadable, C1 { }
let obj1 = MyClassC1()
obj1.download()
// Output:
// Perform download
// Perform save C1
class MyClassC1C2: Downloadable, C1, C2 { }
let obj2 = MyClassC1C2()
obj2.download()
// Output:
// Perform download
// Perform save C1 & C2
Thanks in advance!