Skip to content

Instantly share code, notes, and snippets.

@beccadax
Last active September 28, 2016 06:22
Show Gist options
  • Save beccadax/c084430fc2840f70f3eea938a0d1548e to your computer and use it in GitHub Desktop.
Save beccadax/c084430fc2840f70f3eea938a0d1548e to your computer and use it in GitHub Desktop.
Code that doesn't work because existentials don't conform to their own protocols.
protocol MyNode {
var total: Int { get }
}
protocol MyParentNode: MyNode {
// Each MyParentNode-conforming type can only have certain types of child nodes
// (basically, type A can have B, C, or D; B can have C or D; C can have D; and D is not a MyParentNode).
// I want to model these limitations in the types of children permitted.
associatedtype Child: MyNode
var children: [Child] { get set }
}
extension MyParentNode {
var total: Int {
return children.map { $0.total }.reduce(0, +)
}
}
protocol SpecificNodeChild: MyNode {}
struct SpecificNode: MyParentNode {
typealias Child = SpecificNodeChild
var children: [Child] = []
// Error: Type 'SpecificNode' does not conform to protocol 'MyParentNode'
// Protocol requires nested type 'Child'; do you want to add it?
// Possibly intended match 'SpecificNode.Child' (aka 'SpecificNodeChild') does not conform to 'SpecificNode'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment