Articles  ⏵

Anonymous classes for Swift

2014-07-26

Abstract

All classes, structs and enums in Swift are named and they are concrete in the sense that there are no abstract members, like abstract methods or properties. Especially for classes with very little functionality, it would sometimes be handy to have a lightweight approach to define a single instance of a class or struct. This post introduces a Swift-specific design pattern for creating such lightweight anonymous class and struct instances.

Anonymous class design pattern

Implementing small classes and structs

Let’s assume we would want to implement Java-like iterators in Swift. Swift’s approach to iterators is defined in terms of the GeneratorType protocol:

protocol GeneratorType {

  typealias Element

  mutating func next() -> Element?

}

This protocol defines a function next which returns the elements of a collection of objects incrementally. If no elements are left, next returns nil. All of Swift’s collection classes, like Array<T>, Set<T>, and Dictionary<K, V>, return generators for iterating over their elements. This mechanism is also used for implementing the for loop in Swift.

Java-like iterators are a little more expressive: they also define a hasNext method which returns true if there are more elements left. We could define a corresponding protocol, which is compatible to Swift’s GeneratorType protocol, in the following way:

protocol IteratorType: GeneratorType {

  var hasNext: Bool { get }

}

This protocol defines a hasNext property and inherits function next from GeneratorType.

If we would have to implement iterators for a large number of collection classes, we would have to define a lot of small, very similar classes or structs which implement the IteratorTypeprotocol for a specific collection class.

Here’s an example showing how we can implement an iterator over arrays in Swift: