Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Swift Protocol-Oriented Programming
Swift Protocol-Oriented Programming

Swift Protocol-Oriented Programming: Increase productivity and build faster applications with Swift 5 , Fourth Edition

Arrow left icon
Profile Icon Jon Hoffman
Arrow right icon
£13.98 £19.99
eBook Jun 2019 224 pages 4th Edition
eBook
£13.98 £19.99
Paperback
£24.99
Subscription
Free Trial
Renews at £16.99p/m
Arrow left icon
Profile Icon Jon Hoffman
Arrow right icon
£13.98 £19.99
eBook Jun 2019 224 pages 4th Edition
eBook
£13.98 £19.99
Paperback
£24.99
Subscription
Free Trial
Renews at £16.99p/m
eBook
£13.98 £19.99
Paperback
£24.99
Subscription
Free Trial
Renews at £16.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

Swift Protocol-Oriented Programming

Our Type Choices

In most traditional, object-oriented programming languages, we create classes (which are reference types) as blueprints for our objects. In Swift, unlike other object-oriented languages, structures have much of the same functionality as classes; however, they are value types. Apple has said that we should prefer value types, such as structures, to reference types, but what are the actual advantages? Swift actually has a number of type choices that we can use, and in this chapter we will look at all of these types to see their advantages and disadvantages. Knowing how and when to use each type is important in order to properly implement protocol-oriented programming in our projects.

In this chapter, you will learn the following:

  • What a class is and how to use it
  • What a structure is and how to use it
  • What an enumeration is and how to use it
  • What a tuple is and...

Classes

In object-oriented programming, we cannot create an object without a blueprint that tells the application what properties and methods to expect from the object. In most object-oriented languages, this blueprint comes in the form of a class. A class is a construct that allows us to encapsulate the properties, methods, and initializers of an object into a single type. Classes can also include other items, such as subscripts; however, we are going to focus on the basic items that make up classes, not only in Swift, but in other languages as well.

Let's look at how we would use a class in Swift:

class Myclass {
var oneProperty: String init(oneProperty: String) { self.oneProperty = oneProperty } func oneFunction() { } }

An instance of a class is typically called an object. However, in Swift, structures and classes have many of the...

Structures

Apple has said that Swift developers should prefer value types over reference types, and it seems that they have also taken that philosophy to heart. If we look at the Swift standard library (http://swiftdoc.org), we will see that the majority of types are implemented using structures. The reason Apple is able to implement the majority of Swift's standard library with structures is that, in Swift, structures have many of the same functionalities as classes. There are, however, some fundamental differences between classes and structures, and we will be looking at these differences later in this chapter.

In Swift, a structure is a construct that allows us to encapsulate the properties, methods, and initializers of an instance into a single type. They can also include other items, such as subscripts. However, we are going to focus on the basic items that make up a...

Access controls

Access controls allow us to restrict the access to, and visibility of, parts of the code. This allows us to hide implementation details and only expose the interfaces we want the external code to access. We can assign specific access levels to both classes and structures. We can also assign specific access levels to properties, methods, and initializers that belong to our classes and structures.

In Swift, there are five access levels:

  • Open: This is the most visible access control level. It allows us to use a property, method, class, and so on anywhere we want to import the module. Basically, anything can use an item that has an access control level set to open. Anything that is marked open can be subclassed or overridden by any item within the module they are defined in, and any module that imports the module it is defined in. This level is primarily used by...

Enumerations

In most languages, enumerations are little more than a data type consisting of a set of named values called elements. In Swift, however, enumerations have been supercharged to give them significantly more power. Enumerations in Swift are a lot closer in functionality to classes and structures; however, they can still be used like enumerations in other languages.

Before we see how enumerations are supercharged in Swift, let's see how we can use them as standard enumerations. The following code defines the Devices enumeration:

enum Devices { 
    case iPod  
    case iPhone  
    case iPad 
} 

In the Devices enumeration, we defined three possible values: iPod, iPhone, and iPad. One of the reasons why enumerations are different in Swift, as compared to other languages, is that they can be prepopulated with values known as raw values. As shown in the following code...

Tuples

In Swift, a tuple is a finite, ordered, comma-separated list of elements. While there are tuples in other languages that I have used, I never really took advantage of them. To be honest, I was only vaguely aware that they actually existed in those other languages. In Swift, tuples are more prominent than they are in other languages, which forced me to take a closer look at them. What I found is that they are extremely useful.

In my opinion, tuples are one of the most underutilized types in Swift and, as we go through this book (especially in the case study section), I will point out some cases where the tuple type can be used.

We can create a tuple and access the information within it as follows:

let mathGrade1 = ("Jon", 100)  
let (name, score) = mathGrade1  
print("\(name) - \(score)")  

In the previous code, we grouped a String and an Integer into...

Protocols

To some, it may seem surprising that protocols are considered a type, since we cannot actually create an instance of them; however, we can use them as a type. What this statement means is that, when we define the type for a variable, constant, tuple, or collection, we can use a protocol for that type.

We are not going to cover protocols in depth in this section since we have already covered them in Chapter 1, Starting with the Protocol; however, it is important to understand that they are considered a type.

Each type that we have discussed so far is either a value or a reference type; however, a protocol is neither, because we are not able to create an instance of them.

It is really important to have a complete understanding of the differences between value and reference types in Swift, so let's compare the two.

Value and reference types

There are some fundamental differences between value types (structures, enumerations, and tuples) and reference types (classes). The primary difference is how the instances of value and reference types are passed. When we pass an instance of a value type, we are actually passing a copy of the original instance. This means that the changes made to one instance are not reflected back to the others. When we pass an instance of a reference type, we are passing a reference to the original instance. This means that both references point to the same instance; therefore, a change made to one reference will reflect in the others.

The explanation in the previous paragraph is a pretty straightforward explanation; however, it is a very important concept that you must understand. In this section, we are going to examine the differences between value and reference...

Recursive data types for reference types only

A recursive data type is a type that contains other values of the same type as a property for the type. Recursive data types are used when we want to define dynamic data structures such as lists and trees. The size of these dynamic data structures can grow or shrink, depending on our runtime requirements.

Linked lists are perfect examples of a dynamic data structure that we would implement using a recursive data type. A linked list is a group of nodes that are linked together and where, in its simplest form, each node maintains a link to the next node in the list. The following diagram shows how a very basic linked list works:

Each node in the list contains some value or data, and it also contains the link to the next node in the list. If one of the nodes within the list loses the reference to the next node, the remainder of the list...

Inheritance for reference types only

In object-oriented programming, inheritance refers to one class (known as a sub or child class) being derived from another class (known as a super or parent class). The subclass will inherit methods, properties, and other characteristics from the superclass. With inheritance, we can also create a class hierarchy where we can have multiple layers of inheritance.

Let's look at how we could create a class hierarchy with classes in Swift. We will start off by creating a base class named Animal:

class Animal { 
    var numberOfLegs = 0  
    func sleeps() { 
       print("zzzzz") 
    } 
    func walking() { 
       print("Walking  on \(numberOfLegs) legs") 
    } 
    func speaking() { 
       print("No sound") 
    } 
} 
 

In the Animal class, we defined one property (numberOfLegs) and three methods (sleeps(...

Dynamic dispatch

In the Inheritance for reference types only section, we saw how we can use inheritance with classes to inherit and override functionality defined in a superclass. You may be wondering how and when the appropriate implementation is chosen. The process of choosing which implementation to call is performed at runtime and is known as dynamic dispatch.

One of the key points to understand from the previous paragraph is that the implementation is chosen at runtime. What that means is that a certain amount of runtime overhead is associated with using class inheritance, as shown in the Inheritance for reference types only section. For most applications, this overhead is not a concern; however, for performance-sensitive applications such as games, this overhead can be costly.

One of the ways that we can reduce the overhead associated with dynamic dispatch is to use the...

Swift's built-in types

If you are reading this book, you are probably very familiar with Swift's built-in data types and data structures. However, to really unleash their power, we need to understand how they are implemented in the Swift standard library. The Swift standard library defines several standard data types, such as Int, Double, and String. In most languages, these types are implemented as primitive types, which means that they cannot be extended or subclassed. In Swift, however, these types are implemented in the Swift standard library as structures, which means we can extend these types just as we can with any other type that is implemented as a structure; however, we cannot subclasses them as we can do with other languages.

You can read more about Swift's standard library at http://swiftdoc.org

Swift also defines several standard data structures, such...

COW

When an instance of a value type, such as a structure, is assigned to another variable, that second variable receives a copy of the instance. This means that if we had an array that contained 50,000 elements, then at runtime we would need to copy all 50,000 elements when we assigned the array to a second variable or if we passed it to another part of our code. This can severely impact our performance; however, with Swift built-in data structures such as the array, this impact is reduced because of COW.

With COW, Swift does not make a second copy of the data structure until a change is made to that data structure. Therefore, if we pass an array of 50,000 elements to another part of our code, and that code does not actually make any changes to the array, we will avoid the runtime overhead of copying all the elements.

Unfortunately, COW is only implemented with certain types...

Summary

In most object-oriented programming languages, our type choices are limited. In Swift, however, we have numerous choices. This allows us to use the right type for the right situation. Understanding how the different types work is essential to writing good, stable code.

In this chapter, we looked at the different types we can use in Swift and emphasized the difference between value and reference types. Apple has said that value types should be preferred over reference types. We did look at areas, such as recursive data types, that require reference types.

We also discussed how we can optimize our code by using the final keyword when using reference types. In the next chapter, we will look at how we can avoid using a class hierarchy by using extensions.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Leverage the power of Protocol-Oriented Programming in your applications
  • Leverage generics to create very flexible frameworks
  • Learn how to implement common design patterns in a protocol-oriented way

Description

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.

Who is this book for?

This book is intended for Swift developers who have, at minimum an introductory knowledge of the Swift programming language and would like to understand how they can use Protocol-Oriented Programming techniques in their applications.

What you will learn

  • Learn the differences between object-oriented programming and protocol-oriented programming
  • Understand why value types should be prioritized over reference types
  • Delve into protocols, protocol inheritance, protocol composition, and protocol extensions
  • Learn how to implement COW (Copy-On-Write) within your custom value types
  • Understand how memory management works in Swift and how to avoid common pitfalls
  • Design applications by starting with the protocol rather than the implementation

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 28, 2019
Length: 224 pages
Edition : 4th
Language : English
ISBN-13 : 9781789343670
Vendor :
Apple
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

Publication date : Jun 28, 2019
Length: 224 pages
Edition : 4th
Language : English
ISBN-13 : 9781789343670
Vendor :
Apple
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£16.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
£169.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts
£234.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total £ 91.97
Hands-On Design Patterns with Swift
£36.99
Mastering Swift 5
£29.99
Swift Protocol-Oriented Programming
£24.99
Total £ 91.97 Stars icon

Table of Contents

10 Chapters
Starting with the Protocol Chevron down icon Chevron up icon
Our Type Choices Chevron down icon Chevron up icon
Extensions Chevron down icon Chevron up icon
Generics Chevron down icon Chevron up icon
Memory Management Chevron down icon Chevron up icon
Object-Oriented Programming Chevron down icon Chevron up icon
Protocol-Oriented Programming Chevron down icon Chevron up icon
Adopting Design Patterns in Swift Chevron down icon Chevron up icon
Case Studies Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.