Book Image

Swift Protocol-Oriented Programming - Fourth Edition

By : Jon Hoffman
Book Image

Swift Protocol-Oriented Programming - Fourth Edition

By: Jon Hoffman

Overview of this book

Protocol-oriented programming is an incredibly powerful concept at the heart of Swift's design. Swift's standard library was developed using POP techniques, generics, and first-class value semantics; therefore, it is important for every Swift developer to understand these core concepts and take advantage of them. The fourth edition of this book is improved and updated to the latest version of the Swift programming language. This book will help you understand what protocol-oriented programming is all about and how it is different from other programming paradigms such as object-oriented programming. This book covers topics such as generics, Copy-On-Write, extensions, and of course protocols. It also demonstrates how to use protocol-oriented programming techniques via real-world use cases. By the end of this book, you will know how to use protocol-oriented programming techniques to build powerful and practical applications.
Table of Contents (11 chapters)

Generic subscripts

Prior to Swift version 4, we could use generics with subscripts only if the generic type was defined in the containing type; however, we were unable to define a new generic type within the subscript definition. For example, if we had a List type, we could use the generic type defined by the List type within the subscript, as shown in this example:

struct List<T> { 
    /*  other implementation code here */ 
 
    subscript(index: Int) -> T? { 
        return getItemAtIndex(index: index) 
    } 
}  

With Swift version 4 and later, we are able to define generic types within the subscript definition itself. To see how we would do this, let's go ahead and create another very basic generic List type. The following code shows us how to do this:

struct List<T> { 
    private var items = [T]() 
    public mutating func add(item: T) { 
        items...