Swift Class Clusters

There was an interesting discussion at work today that led to class clusters.

First, I was surprised by the fact that, apparently, class clusters are something only old farts like me are aware of. But the discussion got me wondering: would it be possible to implement a class cluster in Swift?

Well, apparently it is. Let’s say we want to consume this cluster within the module it is declared in. So, by relying on inner types, we coudl do somenthing like this:

//Cell.swift

class Cell {
  private class GreenBackgroundCell: Cell {
    override func doYourThing() {
      print("I'm a green background cell")
    }
  }

  private class RedBackgroundCell: Cell {
    override func doYourThing() {
      print("I'm a red background cell")
    }
  }

  static func cellWithGreenBackground() -> Cell {
    return GreenBackgroundCell()
  }

  static func cellWithRedBackground() -> Cell {
    return RedBackgroundCell()
  }

  func doYourThing() {

  }
}

So, now we could do something like this:

let cell: Cell = Cell.cellWithGreenBackground()
cell.doYourThing()

let anotherCell: Cell = Cell.cellWithRedBackground()
anotherCell.doYourThing()

//The compiler won't allow any of these:
//let cell = Cell.GreenBackgroundCell()
//let cell = GreenBackgroundCell()

Now, the question is: would I ever do this in production code? I am not sure. Are there better ways to simulate a class cluster? I assume there would be, so if you know about them, please shout out in the comments!

Anyway, for those interested, there is a sample project on github

Leave a Reply

Your email address will not be published. Required fields are marked *