Movatterモバイル変換


[0]ホーム

URL:


Packt
Search iconClose icon
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!discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Profile icon
Account
Close icon

Change country

Modal Close icon
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timerSALE ENDS IN
0Days
:
00Hours
:
00Minutes
:
00Seconds
Home> Programming> Protocol Oriented Programming> Swift Protocol-Oriented Programming
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
₹799.99₹1965.99
eBookJun 2019224 pages4th Edition
eBook
₹799.99 ₹1965.99
Paperback
₹2457.99
Subscription
Free Trial
Renews at ₹800p/m
Arrow left icon
Profile Icon Jon Hoffman
Arrow right icon
₹799.99₹1965.99
eBookJun 2019224 pages4th Edition
eBook
₹799.99 ₹1965.99
Paperback
₹2457.99
Subscription
Free Trial
Renews at ₹800p/m
eBook
₹799.99 ₹1965.99
Paperback
₹2457.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Table of content iconView table of contentsPreview 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 mostobject-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 theDevices enumeration:

enum Devices {     case iPod      case iPhone      case iPad }

In theDevices enumeration, we defined three possible values:iPod,iPhone, andiPad. 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 inChapter 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...

Dynamic dispatch

In theInheritance 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 theInheritance 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.

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...

Download code iconDownload 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 iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800billed monthly
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconSimple pricing, no contract
₹4500billed annually
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick iconExclusive print discounts
₹5000billed in 18 months
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick iconExclusive print discounts

Frequently bought together


Swift Protocol-Oriented Programming
Swift Protocol-Oriented Programming
Read more
Jun 2019224 pages
eBook
eBook
₹799.99₹1965.99
₹2457.99
Mastering Swift 5
Mastering Swift 5
Read more
Apr 2019370 pages
Full star icon3.8 (29)
eBook
eBook
₹799.99₹2323.99
₹2904.99
Hands-On Design Patterns with Swift
Hands-On Design Patterns with Swift
Read more
Dec 2018414 pages
Full star icon4.7 (3)
eBook
eBook
₹799.99₹2919.99
₹3649.99
Stars icon
Total9,012.97
Swift Protocol-Oriented Programming
₹2457.99
Mastering Swift 5
₹2904.99
Hands-On Design Patterns with Swift
₹3649.99
Total9,012.97Stars icon

Table of Contents

10 Chapters
Starting with the ProtocolChevron down iconChevron up icon
Starting with the Protocol
Protocol syntax
Protocol inheritance
Protocol composition
Using protocols as a type
Polymorphism with protocols
Type casting with protocols
Associated types with protocols
Delegation
Designing with protocols
Protocols in the Swift standard library
Summary
Our Type ChoicesChevron down iconChevron up icon
Our Type Choices
Classes
Structures
Access controls
Enumerations
Tuples
Protocols
Value and reference types
Recursive data types for reference types only
Inheritance for reference types only
Dynamic dispatch
Swift's built-in types
COW
Summary
ExtensionsChevron down iconChevron up icon
Extensions
Defining an extension
Protocol extensions
Text validation
Extensions with the Swift standard library
Conforming to the Equatable protocol
Summary
GenericsChevron down iconChevron up icon
Generics
Generic functions
Type constraints with generics
Generic types
Associated types
Generic subscripts
COW
Generics in a protocol-oriented design
Generics in the Swift standard library
Summary
Memory ManagementChevron down iconChevron up icon
Memory Management
How ARC works
Strong reference cycles
Unowned references
Weak references
Summary
Object-Oriented ProgrammingChevron down iconChevron up icon
Object-Oriented Programming
What is object-oriented programming?
Requirements for the sample code
Swift as an object-oriented programming language
Issues with object-oriented design
Summary
Protocol-Oriented ProgrammingChevron down iconChevron up icon
Protocol-Oriented Programming
Requirements for the sample code
Swift as a protocol-oriented programming language
Summarizing protocol-oriented programming and object-oriented programming
Differences between object-oriented programming and protocol-oriented programming
Protocol and protocol extensions compared with superclasses
Implementing vehicle types
Using value and reference types
The winner is...
Summary
Adopting Design Patterns in SwiftChevron down iconChevron up icon
Adopting Design Patterns in Swift
What are design patterns?
Creational patterns
Structural design patterns
Behavioral design patterns
Summary
Case StudiesChevron down iconChevron up icon
Case Studies
Logging services
The data access layer
Summary
Other Books You May EnjoyChevron down iconChevron up icon
Other Books You May Enjoy
Leave a review - let other readers know what you think

Recommendations for you

Left arrow icon
Debunking C++ Myths
Debunking C++ Myths
Read more
Dec 2024226 pages
eBook
eBook
₹799.99₹2382.99
₹2978.99
Go Recipes for Developers
Go Recipes for Developers
Read more
Dec 2024350 pages
eBook
eBook
₹799.99₹2382.99
₹2978.99
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (68)
eBook
eBook
₹799.99₹2978.99
₹3723.99
Asynchronous Programming with C++
Asynchronous Programming with C++
Read more
Nov 2024424 pages
Full star icon5 (1)
eBook
eBook
₹799.99₹2502.99
₹3127.99
Modern CMake for C++
Modern CMake for C++
Read more
May 2024502 pages
Full star icon4.7 (12)
eBook
eBook
₹799.99₹2978.99
₹3723.99
Learn Python Programming
Learn Python Programming
Read more
Nov 2024616 pages
Full star icon5 (1)
eBook
eBook
₹799.99₹2382.99
₹2978.99
Learn to Code with Rust
Learn to Code with Rust
Read more
Nov 202457hrs 40mins
Video
Video
₹5585.99
Modern Python Cookbook
Modern Python Cookbook
Read more
Jul 2024818 pages
Full star icon4.9 (21)
eBook
eBook
₹799.99₹3276.99
₹4096.99
Right arrow icon

People who bought this also bought

Left arrow icon
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (68)
eBook
eBook
₹799.99₹2978.99
₹3723.99
Event-Driven Architecture in Golang
Event-Driven Architecture in Golang
Read more
Nov 2022384 pages
Full star icon4.9 (11)
eBook
eBook
₹799.99₹2978.99
₹3723.99
The Python Workshop Second Edition
The Python Workshop Second Edition
Read more
Nov 2022600 pages
Full star icon4.6 (22)
eBook
eBook
₹799.99₹3562.99
₹3872.99
Template Metaprogramming with C++
Template Metaprogramming with C++
Read more
Aug 2022480 pages
Full star icon4.6 (14)
eBook
eBook
₹799.99₹3220.99
₹3500.99
Domain-Driven Design with Golang
Domain-Driven Design with Golang
Read more
Dec 2022204 pages
Full star icon4.4 (19)
eBook
eBook
₹799.99₹2680.99
₹3351.99
Right arrow icon

About the author

Profile icon Jon Hoffman
Jon Hoffman
LinkedIn icon
Jon Hoffman has over 25 years of experience in the field of information technology. Over these years, Jon has worked in the areas of system administration, network administration, network security, application development, and architecture. Currently, Jon works as a senior software engineer for Syn-Tech Systems.Jon has developed extensively for the iOS platform since 2008. This includes several apps that he has published in the App Store, apps that he has written for third parties, and numerous enterprise applications. He has also developed mobile applications for the Android and Windows platforms. What really drives Jon the challenges that the field of information technology provides and there is nothing more exhilarating to him than overcoming a challenge.Some of Jon's other interests are spending time with his family, robotic projects, and 3D printing. Jon also really enjoys Tae Kwon Do, where he and his oldest daughter Kailey earned their black belts together early in 2014, Kim (his wife) earned her black belt in December 2014, and his youngest daughter Kara is currently working towards her black belt.
Read more
See other products by Jon Hoffman
Getfree 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 iconChevron 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 iconChevron 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 iconChevron 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 iconChevron 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 iconChevron 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 iconChevron 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.


[8]ページ先頭

©2009-2025 Movatter.jp