Polymorphism and protocol in swift library

Looking into many swift library, i found that many types that have a common interface are usually not implementing a common protocol. For exemple in Swift-Syntax, ClassDeclSyntax and StructDeclSyntax are basically identical with the same children and the same properties (except one). However there is no common Protocol to unify them and allow one to use indifferently StructDeclSyntax or ClassDeclSyntax. It's the same in SpriteKit and many other library. Is there an architecture reason for that, and if yes which one or is it because they didn't "think" about it?

You don't get much benefit from a protocol unless you (or your users) going to write generic code that abstracts over that protocol. "These two things have a similar interface" is an indication that such generic code would be desirable, but it doesn't guarantee that it would be.

There are some other considerations as well; for something like SpriteKit that predates Swift, the idioms that people have already adopted for using the framework probably don't use protocols, even if some things would be easier to express that way.

1 Like

Is there any cost that I don't see of proactively permitting that the generic code will be use instead of waiting for the need for it. especially if the library is public and therefore its usage unknown?

Yes, protocol abstractions have runtime cost that can't always be optimized away, and generics have DX cost that your users will have to pay even if they never use the protocol directly.



If two types have similar interfaces, and you have an occasion to write code that's generic over them, you're also not beholden to the library to provide the protocol for you. You can define your own protocol that suits the need of your own generic functions, and retroactively extend the library types to conform to it.


DeclSyntaxProtocol doesn't really do the job tho, I think it's more used as a abstract type then an interface

From the doc :

Extension point to add common methods to all DeclSyntax nodes. DO NOT CONFORM TO THIS PROTOCOL YOURSELF!

That's what I usually do. But I was guessing that there is a reason for these "missing" protocols, I just wanted to understand the logic better and improve my own programming by having a better insight of how swift works internally and why people developing those libraries chose to not create them. :slight_smile: