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.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
Swift 4 Programming Cookbook
Swift 4 Programming Cookbook

Swift 4 Programming Cookbook: 50 task-oriented recipes to maximise Swift 4 productivity

eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Swift 4 Programming Cookbook

Building on the Building Blocks

In this chapter, we will cover the following recipes:

  • Bundling variables into tuples
  • Ordering your data with arrays
  • Containing your data with sets
  • Storing key-value pairs with Dictionaries
  • Subscripts for custom types
  • Changing your name with typealias
  • Getting property changing notifications using property observers
  • Controlling access with access control
  • Extending functionality with extensions

Introduction

The last chapter gave us the basic types that form the building blocks of the Swift language. Now we will build on top of this knowledge to create more complex structures using functionalities provided by the Swift standard library.

All the code for this chapter can be found in the GitHub repository at https://github.com/SwiftProgrammingCookbook/BuildingOnTheBuildingBlocks.

Bundling variables into tuples

A tuple is a combination of two or more values that can be treated as one. If you have ever wished you could return more than one value from a function or method, you should find tuples very interesting.

Getting ready

Create a new playground and add the following statement:

import Foundation 

This example uses one function from Foundation. We will delve into Foundation in more detail in Chapter 5, Beyond the Standard Library, but for now, we just need to import it.

How to do it...

Let's say that we are building an app that pulls together...

Ordering your data with arrays

In this chapter, and the last, we were introduced to many different Swift constructs: classes, structs, enums, closures, protocols, and tuples. Yet, rarely will we be dealing with these on their own; we will likely have many instances of these constructs, and we need a way to collect multiple instances in useful data structures. We will examine three collection data structures provided by Swift: arrays, sets, and Dictionaries (often called hash tables in other languages):

In the next few recipes, we'll look at how to use them to store and access elements, and examine their relative characteristics.

How to do it...

First, let's investigate arrays, which are an ordered list of elements...

Containing your data with sets

The next collection type we will look at is a set. Sets differ from arrays in two important ways. The elements in a set are stored unordered, and each unique element is only held once. In this recipe, we will look at how we can create and manipulate sets.

How to do it...

Let's take a look at the following steps:

  1. First, let's look at how sets only store unique elements:
let fibonacciArray: Array<Int> = [1, 1, 2, 3, 5, 8, 13, 21, 34] 
let fibonacciSet: Set<Int> = [1, 1, 2, 3, 5, 8, 13, 21, 34]
print(fibonacciArray.count) // 10
print(fibonacciSet.count) // 9
  1. Elements can be inserted and removed, and you can check whether a set contains an element using the following:
var...

Storing key-value pairs with Dictionaries

The last collection type we will look at is the Dictionary, which is a familiar construct in programming languages, where it is sometimes referred to as a hash table. A dictionary holds a collection of pairings between a key and a value. The key can be any element that conforms to the Hashable protocol (just like elements in a set), and the value can be any type. The contents of a Dictionary are not stored in order, unlike an array; instead, the key is used both when storing a value and as a lookup when retrieving a value.

Getting ready

In this recipe, we will use a Dictionary to store details of people at a place of work. We need to store and retrieve a person's information based...

Subscripts for custom types

From the last few recipes on collection types, we have seen, that their elements are accessed through subscripts. However, it's not just collection types that can have subscripts; your own custom types can provide subscript functionality too.

Getting ready

Let's create a simple game of tic-tac-toe, also known as Noughts and Crosses. To do this, we need a three-by-three grid of positions, with each position being filled by either a nought from Player 1, a cross from Player 2, or nothing. We can store these positions in an array of arrays.

The initial game setup code uses the constructs we covered earlier, so we won't go into its implementation. Enter the following code into a new playground...

Changing your name with typealias

The typealias declaration allows you to create an alias for a type; it does exactly what it says on the tin. You can specify a name that can be used in place of any given type definition. If this type is quite complex, a typealias can be a useful way to simplify its use.

How to do it...

Let's take look at the following steps to understand how to use typealias:

  1. First, let's create something to store in an array--in this instance, a Pug struct:
struct Pug { 
let name: String
}
  1. Now we can create an array that will contain instances of a Pug struct:
let pugs = [Pug]() 
As you may or may not know, the collective noun for a group of pugs is called a grumble.
https://www.reference...

Getting property changing notifications using property observers

You may often find that you would like to know when a property changes its value; maybe you want to update the value of another property, or inform a delegate. In Objective-C, this was often accomplished by writing your own getter and setter, or using Key-Value observing (KVO), but we have native support for property observers in Swift.

Getting ready

To examine property observers, we should create an object with a property that we want to observe. Let's create an object to manage users and a property to hold the current user's name:

class UserManager { 
var currentUserName: String = "Emmanuel Goldstein"
}

We want to present some friendly...

Controlling access with access control

Swift provides fine-grained access control, allowing you to specify the visibility that your code has to the other areas of code. This enables you to be explicit about the interface you provide to other parts of the system, encapsulating implementation logic and helping to separate the areas of concern.

Swift has five access levels:

  • Private: Only accessible within the existing scope (defined by curly brackets) or extensions in the same file
  • File private: Accessible to anything in the same file, but nothing outside the file
  • Internal: Accessible to anything in the same module, but nothing outside the module
  • Public: Accessible both inside and outside the module, but cannot be subclassed or overwritten outside of the defining module
  • Open: Accessible everywhere, with no restrictions on its use

These can be applied to types, properties, and functions...

Extending functionality with extensions

Extensions let us add functionalities to the existing classes, structs, enums, and protocols. This can be especially useful when the original type is provided by an external framework, and therefore you aren't able to add a functionality directly.

Getting ready

Imagine that we often need to obtain the first word from a given string. Rather than repeatedly writing the code to split the string into words and then retrieving the first word, we can extend the functionality of String to provide its own first word.

How to do it...

...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Write robust and efficient code and avoid common pitfalls using Swift 4
  • Get a comprehensive coverage of the tools and techniques needed to create multi-platform apps with Swift 4
  • Packed with easy-to-follow recipes, this book will help you develop code using the latest version of Swift

Description

Swift 4 is an exciting, multi-platform, general-purpose programming language. Being open source, modern and easy to use has made Swift one of the fastest growing programming languages. If you interested in exploring it, then this book is what you need. The book begins with an introduction to the basic building blocks of Swift 4, its syntax and the functionalities of Swift constructs. Then, introduces you to Apple's Xcode 9 IDE and Swift Playgrounds, which provide an ideal platform to write, execute, and debug the codes thus initiating your development process. Next, you'll learn to bundle variables into tuples, set order to your data with an array, store key-value pairs with dictionaries and you'll learn how to use the property observers. Later, explore the decision-making and control structures in Swift and learn how to handle errors in Swift 4. Then you'll, examine the advanced features of Swift, generics and operators, and then explore the functionalities outside of the standard library, provided by frameworks such as Foundation and UIKit. Also, you'll explore advanced features of Swift Playgrounds. At the end of the book, you'll learn server-side programming aspect of Swift 4 and see how to run Swift on Linux and then investigate Vapor, one of the most popular server-side frameworks for Swift.

Who is this book for?

If you are looking for a book to help you learn about the diverse features offered by Swift 4 along with tips and tricks to efficiently code and build applications, then this book is for you. Basic knowledge of Swift or general programming concepts will be beneficial.

What you will learn

  • Explore basic to advanced concepts in Swift 4 Programming
  • Unleash advanced features of Apple s Xcode 9 IDE and Swift Playgrounds
  • Learn about the conditional statements, loops, and how to handle errors in Swift
  • Define flexible classes and structs using Generics, and learn about the advanced operators, and create custom operators
  • Explore functionalities outside of the standard libraries of Swift
  • Import your own custom functionality into Swift Playgrounds
  • Run Swift on Linux and investigate server-side programming with the server side framework Vapor

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 28, 2017
Length: 384 pages
Edition : 1st
Language : English
ISBN-13 : 9781786460899
Vendor :
Apple
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Sep 28, 2017
Length: 384 pages
Edition : 1st
Language : English
ISBN-13 : 9781786460899
Vendor :
Apple
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 136.97
Swift 4 Protocol-Oriented Programming
$43.99
Test-Driven iOS Development with Swift 4
$43.99
Swift 4 Programming Cookbook
$48.99
Total $ 136.97 Stars icon
Banner background image

Table of Contents

8 Chapters
Swift Building Blocks Chevron down icon Chevron up icon
Building on the Building Blocks Chevron down icon Chevron up icon
Data Wrangling with Swift Control Flow Chevron down icon Chevron up icon
Generics, Operators, and Nested Types Chevron down icon Chevron up icon
Beyond the Standard Library Chevron down icon Chevron up icon
Swift Playgrounds Chevron down icon Chevron up icon
Server-Side Swift Chevron down icon Chevron up icon
Performance and Responsiveness in Swift Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(5 Ratings)
5 star 60%
4 star 20%
3 star 20%
2 star 0%
1 star 0%
m c m Jul 19, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
cooking
Amazon Verified review Amazon
Mark Bridges Oct 31, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Really great book for anyone wanting to learn more about Swift, or iOS in general for that matter. Everything’s split up into small ordered ‘recipes’ so it’s easy to quickly refer to things you want to know a bit more about. I feel as though I finally have a clear understanding of the difference between the ‘heap’ and the ‘stack’.
Amazon Verified review Amazon
Kathleen M Moon Aug 29, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
easy to follow - very helpful
Amazon Verified review Amazon
Lionel Carre Mar 16, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Je suis au chapitre 4, j'ai trouvé une petite erreur mais j'ai beaucoup appris. Il me faudra un autre livre pour la programmation des fonctions OS. Mais pour la programmation Swift 4, ce livre est suffisant
Amazon Verified review Amazon
mrbennopolis Nov 04, 2017
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Overall it's a good book, Mr Moon clearly knows the material and has a more sophisticated pedagogical style as these types of writers go. However, the book has typo after typo after typo. To the extent that it's rather annoying and even confuses the concepts he is attempting to convey at points. I don't know if Packt has never heard of copy editing or just don't have any employees who know how to do it. Out of the 100 or so technical books I've read in my life this quite easily is the one with the most grammatical errors. Hopefully they can get their act together reduce this sort of thing going forward. I wouldn't let this stop you from buying the book but it will be a significant annoyance as you work through it.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.