Designing Software with Swift (Part I)

DZone 's Guide to

Designing Software with Swift (Part I)

The newest version of Swift offers multiple ways to design software, and we're not entirely sure which ones are best. Read on to find out what some of these method are, how they compare to other languages, and how they're implemented in Swift.

· Mobile Zone ·
Free Resource

Well, my original plan was to start with various presentation patterns. Especially since the only consistent element in presentation pattern implementations it seems is that they’re done wrong. And since I was planning on showing you multiple ways to solve the same problems with different approaches, it makes sense to start the series with an overview of everybody’s favorite pattern: Observer. And since Observer is key to so many presentation patterns, well, we’re going to go ahead and cover it first.

Before we get started with implementing an example of the Observer pattern in Swift, let’s first talk a bit about protocol- v. type-based programming. So Swift was originally built as a protocol-first language. Protocols allow you to define a wide range of object behaviors, and via self or typealias supply developers with some range of type genericicity. It also has a powerful generics capability, very similar to Java’s notationally.

We’ve seen this before in other languages, this juxtaposition of Generics and Protocols (or Interfaces). Java has this. So does C++. And they’ve evolved differently in both communities.

Now, templates in C++ are arguably more powerful and certainly much more confusing that generics in Java. In the Java world, generics and interfaces have evolved side-by-side, each filling particular places in each engineer’s design pallette. C++ is a bit different. First, interfaces in C++ are really pure abstract classes rather than interfaces per se (though the difference is virtually meaningless). This gives both environments the ability to use runtime polymorphism, with delayed object binding, or compile-time polymorphism.

We’ve seen more extensive use of templates in software design in C++, though we’ve certainly seen a maintreaming of generics in Java system design too. In the C++ world though, we’ve seen template-based design and meta-programming become design options as well.

Swift has these same kinds of design primitives, though Protocols have yet to support truly generic types (they do support Self and typealias, though). You can certainly use Protocols with Generics in Swift. I’m going to show dynamic and compile time polymorphism design options, show how they complement each other, and then how you can use both to get the best of both worlds in your code.

I'll compare and contrast different ways to design software using these approaches in upcoming articles. Stay tuned.

design, patterns, swift

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}