Designing Software With Swift (Part III): Type-Based Design Without Protocols

DZone 's Guide to

Designing Software With Swift (Part III): Type-Based Design Without Protocols

Look over another design option in Swift, and learn why it's maybe better than you'd expect.

· Mobile Zone ·
Free Resource

So let’s take a look at type-based design. First, we'll look at a generic system designed without protocols. This sounds like a mistake, but honestly, generics and protocols don't play together well, so why not? As opposed to using protocol-based reuse, we'll lean on generics instead.

We'll design and Observer and a Subject, where the Subject notifies registered Observers of state changes.

public class Observer<T> {

  let name : String = String(arc4random_uniform(10000))

  public func update(data: T) {
  print("updated: \(data)")

public final class Subject<T, S: Hashable> {

  private var observers : [S: Observer<T>] = [:]

  private var data : T?

  public var state : T? {
    get {
      return data
    set(data) {
      self.data = data

  public func attach(k: S, o: Observer<T>) {
    observers[k] = o

  public func detach(k: S) {

  private func notify() {
    if let mydata = data {
      for (_, observer) in observers {

The first system, using generic typing without protocols. This is very simple. A good thing! simple software tends to be underrated. It's easier to test, easier to build, and easier to understand. As software engineers, we're all guilty of overdesigning code at least once in our careers (especially if we've worked with Java, amirite?). Simple software is much cheaper to build and maintain, even if it seems not to be as reusable or flexible. But honestly, is that a big deal? After all, we all know you're not going to need it (yes, YAGNI, worst acronym ever).

Anyway, we run the system like this:

var o = Observer<String>()
var s = Subject<String, String>()
s.attach(o.name, o: o)
s.state = "state change!"

This produces the output you’d expect. Nice, consice and clean. Let's see how we can make this more complex next.

design, pattern, swift

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}