The expression problem is a well-known programming challenge. Let’s explore it in Swift by trying to model an arithmetic operation like this one: Th

The Expression Problem in Swift

submited by
Style Pass
2024-12-22 17:30:02

The expression problem is a well-known programming challenge. Let’s explore it in Swift by trying to model an arithmetic operation like this one:

This approach makes it extremely easy to add new arithmetic operations just by having a new type conform to the Operation protocol.

But what about trying to add a new “interpretation” for that arithmetic operation? Right now, we only compute the final number after evaluating the operation, but we might want to “interpret” the operation differently. For instance, we might want to present the user with the string representation of the operation, that is, something like 3+5*(8-7)/6.

Well, that’s slightly trickier. If we had access to the Operation type, we might simply add a new asString property and have all the conformant types implement that new method. But Operation could be defined in an external library we don’t have access to. What options do we have then? Well, we have extensions…

Of course, that doesn’t work and the last line ends up hitting the fatalError. Even if the asString method inside the Add type is called, the lhs and rhs variables are Operation types. As asString method is only defined in a protocol extension and not as a required method in the protocol definition, the dispatch of the asString method for lhs and rhs will be static, not dynamic. What that means is that the underlying runtime type for lhs and rhs won’t matter and Number‘s asString implementation won’t be ever called. Rather, the fatalError will.

Leave a Comment