Reputation: 797
Is it possible to implement a protocol or protocol extension that specifies that the protocol will only be used for classes & that those classes have super classes ?
If so, can I leverage this to have a function that iterates down through a class's superclasses to gather all of the data they each is storing one common variable ?
In other words, in the example below is it possible to create an extension that does what the second BaseType extension pseudocode is trying to do such that at the end allVals = ["core", "middle", "top"]
?
import Foundation
protocol BaseType: class {
var data: [String] { get }
var all: [String] { get }
}
extension BaseType {
var all: [String] {
return data
}
}
// Is the intent of this extension realistic?
extension BaseType where Self.super is BaseType {
var all: [String] {
return data + super.all
}
}
class CoreDT: BaseType {
var core: String = "core"
var data: [String] { return [core] }
}
class MiddleDT: CoreDT {
var middle: String = "middle"
override var data: [String] { return [middle] }
}
class TopDT: MiddleDT {
var top: String = "top"
override var data: [String] { return [top] }
}
let allVals = TopDT().all
print(allVals)
Upvotes: 0
Views: 2122
Reputation: 309
You cannot achieve this.
You can only achieve the functionality to work with superclass inside protocol by implementing NSObjectProtocol above it. But then, the problem with the bridged functions from Objective C to Swift will appear. The solution will be tomake the protocol an @objc protocol, but then you will not be able to extend it with default implementation.
Upvotes: 1