Book Image

Swift 4 Protocol-Oriented Programming - Third Edition

By : Jon Hoffman
Book Image

Swift 4 Protocol-Oriented Programming - Third Edition

By: Jon Hoffman

Overview of this book

Swift has become the number one language used in iOS and macOS development. The Swift standard library is developed using protocol-oriented programming techniques, generics, and first-class value semantics; therefore, every Swift developer should understand these powerful concepts and how to take advantage of them in their application design. This book will help you understand the differences between object-oriented programming and protocol-oriented programming. It will demonstrate how to work with protocol-oriented programming using real-world use cases. You will gain a solid knowledge of the various types that can be used in Swift and the differences between value and reference types. You will be taught how protocol-oriented programming techniques can be used to develop very flexible and easy-to-maintain code. By the end of the book, you will have a thorough understanding of protocol-oriented programming and how to utilize it to build powerful and practical applications.
Table of Contents (15 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Generics in a protocol-oriented design


Now that we have seen how to use generics, let's see how we can use them in a protocol-oriented design. In a previous example in this chapter, we created a generic List type, however, we can greatly improve on this design by using what we learned throughout this chapter. We will include only a small subset of the actual requirements for a List type so we can focus on the design rather than all the requirements.

With a protocol-oriented design, we always start with the protocol. The following code shows the List protocol:

protocol List {
  associatedtype T
  subscript<E: Sequence>(indices: E) -> [T]
      where E.Iterator.Element == Int { get }
  mutating func add(_ item: T)
  func length() -> Int
  func get(at index: Int) -> T?
  mutating func delete(at index: Int)
}

We start the List protocol by defining the associated type T. This associated type will be the type of data stored in the list. We use the T type as the parameter for the add...