Over a million developers have joined DZone.

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

Visually compose APIs with easy-to-use tooling. Learn how IBM API Connect provides near-universal access to data and services both on-premises and in the cloud, brought to you in partnership with IBM.

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.

The Mobile Zone is brought to you in partnership with Strongloop and IBM.  Visually compose APIs with easy-to-use tooling. Learn how IBM API Connect provides near-universal access to data and services both on-premises and in the cloud.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}