Background:
I'm trying to build an OutlineGroup from this example from Apple: https://developer.apple.com/documentation/swiftui/outlinegroup
But instead of using static types I want to use objects that conform to my protocol. So the question is more general if that's possible in swift what I'm trying to do:
Problem:
I have protocol that gives me people coworkers and name from various objects:
protocol CastProtocol {
var name: String { get }
var coworkers: [CastProtocol]? { get } // here will be the build error later
}
And consider two models as example:
class Actor: Identifiable, CastProtocol {
var id: Self { self }
var name: String { return "Chuck Norris" }
var coworkers: [CastProtocol]? {
return [
Director()
]
}
}
class Director: Identifiable, CastProtocol {
var id: Self { self }
var name: String { return "Gina Carey" }
var coworkers: [CastProtocol]? {
return [
Actor(),
Director(),
Actor()
]
}
}
So till now everything working, but I need to ensure that my CastProtocol conforms to Identifiable, so changing my protocol implementation to:
protocol CastProtocol: Identifiable {
...
}
And now this creates a problem:
Protocol 'CastProtocol' can only be used as a generic constraint because it has Self or associated type requirements
Questions:
- So there is a way to do this with return not static type in
coworkersor maybe I should go with subclassing? - Is that a correct approach? Maybe the only thing I'm missing is declare in protocol level identifier requirements for identifiable? But if so - how to do it?
- I cannot really go with associatedType I think. If
coworkersin this example can containActororDirectorassociatedType I think cannot be use