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

Extensions with the Swift standard library


Let's say that, in our application, we needed to calculate the factorial of some integers. A factorial is written as 5!. To calculate a factorial, we take the product of all the positive integers that are less than or equal to the number. The following example shows how we would calculate the factorial of five:

5! = 5*4*3*2*1 
5! = 120 

We could very easily create a global function to calculate the factorial, and we would do that in most languages, however, in Swift, extensions give us a better way to do this. The Integer type in Swift is implemented as a structure which we can extend to add this functionality directly to the type itself. The following example shows how we can do this:

extension Int { 
  func factorial() -> Int {  
    var answer = 1 
    for x in (1...self).reversed() {  
      answer *= x 
    } 
    return answer 
  } 
} 

We could now calculate the factorial of any integer, as follows:

print(10.factorial()) 

If we run this code...