Skip to content

Instantly share code, notes, and snippets.

@pcantrell
Created November 13, 2017 16:12
Show Gist options
  • Save pcantrell/131295b96e01409aff28e863ed88c175 to your computer and use it in GitHub Desktop.
Save pcantrell/131295b96e01409aff28e863ed88c175 to your computer and use it in GitHub Desktop.
// Siesta’s Resource class represents the current “best information available”
// about a RESTful resource. Other parts of the code can observe changes to
// that state (started loading, received new data, received error, etc):
public protocol ResourceObserver
{
func resourceChanged(_ resource: Resource, event: ResourceEvent)
// (plus other stuff I’m ignoring)
}
class HappyControllerDoodad: ResourceObserver
{
func resourceChanged(_ resource: Resource, event: ResourceEvent)
{ … }
}
// In a future version of Siesta, I’d like to add a type param to Resource
// that describes what kind of content/model it holds, say for example
// Resource<Article> vs Resource<Comment>. With generic protocols, I imagine
// one could do this:
class HappyControllerDoodad: ResourceObserver<Article>, ResourceObserver<Comment>
{
func resourceChanged(_ resource: Resource<Article>, event: ResourceEvent)
{ /* update article view */ }
func resourceChanged(_ resource: Resource<Comment>, event: ResourceEvent)
{ /* update comment view */ }
}
// Associated types prevent this kind of multiple conformance, of course.
// With generalized existentials, this alternative would still be possible:
class HappyControllerDoodad: ResourceObserver<Article>, ResourceObserver<Comment>
{
func resourceChanged(_ resource: Resource, event: ResourceEvent)
{
switch resource
{
case is Resource<Article>:
// update article view
case is Resource<Comment>:
// update article view
default:
fatalError("What is this madness?!")
}
}
}
// …but that's markedly inferior to my eyes.
//
// HOWEVER
//
// The reason I haven’t already done this whole Resource<T> thing is that
// without generalized existentials it's … well, not technically impossible,
// but just too stupidly awkward in practice. I tried it, and it’s not pretty.
//
// So even though I'd like generic protocols, I want generalized existentials
// far, far, far more.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment