0

I have a pretty simple class structure where an "abstract" base class, Node, is implemented in a few concrete subclasses. In my case the base class represents the common interface to the object and therefore most type references are purely Node for simplicity.

However what I want to do now is implement support for ExpressibleByStringLiteral on the abstract Node such that I can instantiate a specific (of my choosing) concrete subclass when a String is interpreted as a Node.

The problem is ExpressibleByStringLiteral doesn't seem to want to allow me to do this because it requires I implement a required initializer as opposed to a static function (which would make way more sense, imo). I've gotten it able to work on one of the concrete subclasses, but that's pretty useless to me given that the concrete type is rarely used explicitly (and in fact I'd prefer it not be), as everything goes through the base Node type.

What I want is to be able to do this:

let node: Node = "textual representation of a node"

Since the subclasses are still Nodes, this doesn't violate any object oriented principles, yet Swift doesn't seem to want to let me do it.

Is there any way around this, or is this just a limitation of ExpressibleByStringLiteral?

devios1
  • 36,899
  • 45
  • 162
  • 260
  • Swift doesn't have abstract classes, do you mean Protocols? – fpg1503 Jun 13 '17 at 20:20
  • I just mean conceptually it's abstract, as in never instantiated directly. – devios1 Jun 13 '17 at 20:21
  • 1
    In that case yes, it's a Swift limitation, you could wrap an instance of the subclass in a property and forward all method calls and properties but it looks like a hack to me, I'd use a factory in that case (but you'll lose the `ExpressibleByStringLiteral` advantages :/) – fpg1503 Jun 13 '17 at 20:24
  • 1
    Take a look at [this question](https://stackoverflow.com/q/24014122/2305521) – fpg1503 Jun 13 '17 at 20:25
  • 1
    Class clusters or factory initializers in Swift would be awesome. I kind of wish we could just go back to how initializers worked in Objective-C; they're so complicated in Swift. – devios1 Jun 13 '17 at 20:37

0 Answers0