Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Swift Cookbook - Third Edition
Swift Cookbook - Third Edition

Swift Cookbook: Proven recipes for developing robust iOS applications with Swift 5.9, Third Edition

By Chris Barker , Daniel Bolella , Mr. Keith Moon , Nathan Lawlor
$35.99 $24.99
Book Jun 2024 422 pages 3rd Edition
eBook
$35.99 $24.99
Print
$44.99
Subscription
Free Trial
Renews at $15.99p/m
eBook
$35.99 $24.99
Print
$44.99
Subscription
Free Trial
Renews at $15.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
Table of content icon View table of contents Preview book icon Preview Book

Swift Cookbook - Third Edition

Swift Fundamentals

Since Apple announced the Swift programming language back in 2014 at the Worldwide Developer Conference (WWDC), it has gone on to become one of the fastest-growing programming languages.

Swift is a modern, general-purpose programming language that focuses on type safety and expressive and concise syntax. Positioned as a modern replacement for Objective-C, it has taken over from Apple’s older language as the future of development across all their platforms.

Since open-sourcing Swift, Apple has provided support for running your Swift code on a whole host of platforms including Linux. Despite these alternative ways to use and write Swift code, the simplest is still on a Mac using Apple’s Xcode.

In this chapter, we will look at the fundamentals of the Swift language and examine the syntax and functionality of the basic Swift component.

In this chapter, we will cover the following recipes:

  • Writing your first code in Swift
  • Using the...

Technical requirements

We will walk you through setting up Xcode 15.0 and use this development environment unless otherwise stated. Xcode 15.0 can be downloaded from the Apple App Store on a Mac running the latest OS.

We will be using Swift 5.9. This version will also be more compatible with future versions of Swift, which means that code written now with Swift 5.9 can run alongside code written with future versions of Swift.

We will be using Playgrounds in Xcode to implement the recipes contained in this book unless otherwise stated. The benefit of using Xcode Playgrounds is its simplicity of quickly writing and compiling Swift syntax.

All the code for this chapter can be found in the book’s GitHub repository at https://github.com/PacktPublishing/Swift-Cookbook-Third-Edition/tree/main/Chapter%201.

Writing your first code in Swift

In this recipe, we’ll get you started with the Xcode integrated development environment (IDE) and get you ready to write your first lines of Swift code… buckle up!

Getting ready

For this recipe, you will need Xcode 15 or newer.

How to do it…

Once you have successfully downloaded Xcode from the Apple App Store, we’ll need to launch the application:

  1. Launch Xcode from the dock or via the Apple App Store, as shown in the following screenshot:
Figure 1.1 – Xcode in the App Store

Figure 1.1 – Xcode in the App Store

  1. You’ll be presented with the following splash screen:
Figure 1.2 – Xcode splash screen

Figure 1.2 – Xcode splash screen

  1. From here, in the toolbar on your Mac, click File > New > Playground…:
Figure 1.3 – Selecting Playground…

Figure 1.3 – Selecting Playground…

  1. Select Blank from the iOS tab and press Next:
Figure 1.4 – Choose Blank, but notice the other options

Figure...

Using the basic types – strings, ints, floats, and booleans

Many of the core operations in any programming language involve manipulating text and numbers, and determining true and false statements.

Let’s learn how to accomplish these operations in Swift by looking at its basic types and learning how to assign constants and variables. In doing so, we will touch upon Swift’s static typing and mutability system.

Getting ready

Just like we did in the previous recipe, open Xcode and create a new playground (again, call it what you want).

How to do it…

Let’s start by writing some code that explores the basic types available to us in Swift.

  1. Write the following code into your newly opened Swift Playground; we’ll start with an example of Strings:
    let phrase: String = "The quick brown fox jumps over the lazy dog"
  2. Now, let’s add an example of an integer:
    let numberOfFoxes: Int = 1
    let numberOfAnimals: Int = 2

    The...

Reusing code in functions

Functions are a building block of almost all programming languages, allowing functionality to be defined and reused.

Swift’s syntax provides an expressive way to define your functions, creating concise and readable code.

In this recipe, we will run through the different types of functions we can create and understand how to define and use them.

Getting ready

In this recipe, we can use the playground from the previous recipe. Don’t worry if you didn’t work through the previous recipe, as this one will contain all the code you need.

How to do it…

Let’s look at how functions are defined in Swift:

func nameOfFunction(parameterLabel1 parameter1: ParameterType1, parameterLabel2 parameter2: ParameterType2,...) -> OutputType {
    // Function's implementation
    // If the function has an output type,
    // the function must return a valid value...

Encapsulating functionality in object classes

Object-oriented programming (OOP) is a programming paradigm common to most software development. At its core is the object class. Objects allow us to encapsulate data and functionality, which can then be stored and passed around.

In this recipe, we will build some class objects, to break down their components, and understand how they are defined and used.

Getting ready

In this recipe, we can use the playground from the previous recipe. Don’t worry if you didn’t work through the previous recipe, as this one will contain all the code you need.

How to do it…

Let’s write some code to create and use class objects, and then we will walk through what the code is doing:

  1. First, let’s create a Person class object:
    class Person {
    }
  2. Within the curly brackets, { }, add three constants representing the person’s name, and one variable representing their country of residence:
    let givenName...

Bundling values into structs

Class objects are great for encapsulating data and functionality within a unifying concept, such as a person, as they allow individual instances to be referenced. However, not everything is an object.

We may need to represent data that is logically grouped together, but there isn’t much more than that. It’s not more than the sum of its parts; it is the sum of its parts.

For this, there are structs. Short for structures, structs can be found in many programming languages. Structs are value types (as opposed to classes, which are reference types) and, as such, behave differently when passed around. In this recipe, we will learn how structs work in Swift, and when and how to use them.

Getting ready

In this recipe, we will build on top of the previous recipe, so open the playground you have used for the previous recipe. Don’t worry if you didn’t work through the previous recipe, as this one will contain all the code you...

Enumerating values with enums

An enumeration is a programming construct that lets you define a value type with a finite set of options. Most programming languages have enumerations (usually abbreviated to enums), although the Swift language takes the concept further than most.

An example of an enum from the iOS/macOS SDK is ComparisonResult, which you would use when sorting items. When comparing for the purposes of sorting, there are only three possible results from a comparison:

  • Ascending: The items are ordered in ascending order
  • Descending: The items are ordered in descending order
  • Same: The items are the same

There are a finite number of possible options for a comparison result; therefore, it’s a perfect candidate for being represented by an enum:

enum ComparisonResult : Int {
    case orderedAscending
    case orderedSame
    case orderedDescending
}

Swift takes the enum concept and...

Passing around functionality with closures

Closures are also referred to as anonymous functions, and this is the best way to explain them. Closures are functions without a name and, like other functions, they can take a set of input parameters and can return an output.

Closures behave like other primary types. They can be assigned, stored, passed around, and used as input and output to functions and other closures.

In this recipe, we will explore how and when to use closures in our code.

Getting ready

We will continue to build on our contacts app example from earlier in this chapter, so you should use the same playground as in the previous recipes.

If, however, you are implementing this in a new playground, first add the relevant code from the previous recipes:

struct PersonName {
    let givenName: String
    let middleName: String
    var familyName: String
    func fullName() ->...

Using protocols to define interfaces

Protocols are a way to describe the interface that a type provides. They can be thought of as a contract, defining how you can interact with instances of that type.

Protocols are a great way to abstract what something does from how it does it. As we will see in subsequent chapters, Swift adds functionalities to protocols that make them even more useful and powerful than in many other programming languages.

Getting ready

We will continue to build on examples from the previous recipes, but don’t worry if you haven’t followed these recipes yet as all the code you need is listed in the upcoming sections.

How to do it…

In the previous recipe, we added a method to our Person class that (given the full implementation) would save it to a remote database. This is a very useful functionality, and as we add more features to our app, there will likely be more types that we also want to save to a remote database:

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

Key benefits

  • Harness the power of Swift to create stunning applications, spanning mobile apps to machine learning models
  • Learn and practice the flexible Swift programming language with a practical, recipe-based approach
  • Leverage the new features in the latest release of Swift and iOS
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Unlock the full potential of Swift and elevate your iOS development skills with this new edition of Swift Cookbook, highlighting the latest features in Swift 5.9. This cookbook will take your Swift programming skills to the next level, boosting your productivity and efficiency step by step through a plethora of practical recipes. Although this book is primarily for experienced iOS developers, it provides an introductory overview of Swift 5.9, including its basic building blocks, syntax, and the functionalities of Swift constructs, to get you warmed up. Once you’ve mastered the fundamentals, you’ll get down to business. Unless you’re completely new to Swift, this recipe-based guide doesn’t need to be read in order; you can jump to whichever topic takes your fancy, from UIKit and SwiftUI to advanced UI techniques, from Swift’s control flow and generics to machine learning with Vision, CoreML, and augmented reality with ARKit. By the end of this book, you’ll be fully up to speed with Swift’s capabilities and be able to develop amazing applications across a wide variety of domains.

What you will learn

Define flexible classes and structs using generics Use advanced operators and create custom ones Build iOS apps using UIKit and SwiftUI framework Import custom functionality into Swift Playgrounds Implement machine learning models using CoreML and Vision Manage 3D models and assets for ARKit using Swift and Xcode

Product Details

Country selected

Publication date : Jun 7, 2024
Length 422 pages
Edition : 3rd Edition
Language : English
ISBN-13 : 9781803239583
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 Details


Publication date : Jun 7, 2024
Length 422 pages
Edition : 3rd Edition
Language : English
ISBN-13 : 9781803239583
Vendor :
Apple
Category :
Languages :
Tools :

Table of Contents

15 Chapters
Preface Chevron down icon Chevron up icon
1. Chapter 1: Swift Fundamentals Chevron down icon Chevron up icon
2. Chapter 2: Mastering the Building Blocks Chevron down icon Chevron up icon
3. Chapter 3: Data Wrangling with Swift Chevron down icon Chevron up icon
4. Chapter 4: Generics, Operators, and Nested Types Chevron down icon Chevron up icon
5. Chapter 5: Beyond the Standard Library Chevron down icon Chevron up icon
6. Chapter 6: Understanding Concurrency in Swift Chevron down icon Chevron up icon
7. Chapter 7: Building iOS Apps with UIKit Chevron down icon Chevron up icon
8. Chapter 8: Building iOS Apps with SwiftUI Chevron down icon Chevron up icon
9. Chapter 9: Getting to Grips with Combine Chevron down icon Chevron up icon
10. Chapter 10: Using CoreML and Vision in Swift Chevron down icon Chevron up icon
11. Chapter 11: Immersive Swift with ARKit and Augmented Reality Chevron down icon Chevron up icon
12. Chapter 12: Visualizing Data with Swift Charts Chevron down icon Chevron up icon
13. Index Chevron down icon Chevron up icon
14. Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Top Reviews
No reviews found
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.