O'Reilly logo

Object–Oriented Programming with Swift 2 by Gastón C. Hillar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a data repository with generics and protocols

Now, we want to create a repository that provides us with entities so that we can apply the functional programming features included in Swift to retrieve and process data from these entities. First, we will create an EntityProtocol protocol that defines the requirements for an entity. We want any class that conforms to this protocol to have a read-only id property of the Int type to provide a unique identifier for the entity:

public protocol EntityProtocol {
    var id: Int { get }
}

The next lines create a Repository<T> generic class that specifies that T must conform to the recently created EntityProtocol protocol in the generic type constraint. The class declares a getAll method that we will ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required