Search icon CANCEL
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

eBook
€13.98 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
Estimated delivery fee Deliver to Ireland

Premium delivery 7 - 10 business days

€23.95
(Includes tracking information)

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 : 9781789349023
Vendor :
Apple
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
Estimated delivery fee Deliver to Ireland

Premium delivery 7 - 10 business days

€23.95
(Includes tracking information)

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela