Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Mastering macOS Programming
Mastering macOS Programming

Mastering macOS Programming: Hands-on guide to macOS Sierra Application Development

Arrow left icon
Profile Icon Gregory Casamento Profile Icon Stuart Grimshaw
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2 (6 Ratings)
Paperback May 2017 626 pages 1st Edition
eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Gregory Casamento Profile Icon Stuart Grimshaw
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2 (6 Ratings)
Paperback May 2017 626 pages 1st Edition
eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$27.98 $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

Mastering macOS Programming

Basic Swift

So, let's get going with a rapid rundown of Swift's basic types and syntax. As befits a book aimed at developers with some experience of programming under their belts, this chapter will not be about the basics of programming, but simply an overview of what we will assume you know as we move through the following chapters. Think of it as a kind of Swift comments cheat-sheet, if you like.

You already understand something of variable declaration, control flow, arrays and dictionaries, and functions. Make sure you fully understand everything that is presented in this chapter, and if there are any concepts you don't understand by the end of it, it's probably a good idea to delve into them somewhat before moving on to Chapter 5, Advanced Swift.

I have tried in this chapter to flag a few typical gotchas that occur when coming from other languages or earlier versions of Swift. Some of...

Variables and types

We can declare variables as follows:

var a: Int = 1

In the preceding line of code, a is declared to be of type Int, with a value of 1. Since only an Int can be assigned the value 1, Swift can automatically infer the type of a, and it is not necessary to explicitly include the type information in the variable declaration:

var a = 1

In the preceding code, it is equally clear to both Swift and the reader what type a belongs to.

What, no semicolons?
You can add them if you want to, and you'll have to if you want to put two statements on the same line (why would you do that?). But no, semicolons belong to C and its descendants, and despite its many similarities to that particular family of languages, Swift has left the nest.

The value of a var can be changed by simply assigning to it a new value:

var a = 1 
a = 2

However, in Swift, we can also declare a constant, which is immutable, using the...

Comments

Swift has adopted C-style comments of both forms:

// We have used this one already 
// in previous sections of this chapter

When it starts to get messy, with // at the beginning of each commented line, we have the following multiline comments:

/* 
This is a multiline
comment, for those times when
you just can't say it
in a few words
*/

Unlike some languages, you can nest these comments, which is handy if you need to comment out a large section of code that itself contains comments:

/* 
Comments can be nested,
/*
like this one
*/
which can be helpful.
*/

Arrays, dictionaries, and sets

Swift offers a comprehensive set of collection types, as one would expect. In common with many other languages, each of these collection types will only hold values of the same type. Thus, the type of an Array of Int values is distinct from the type of an Array of Float values, for example. If you're coming from Objective C, you may quickly come to appreciate the type safety and simplicity of Swift Array objects over NSArray.

There are no separate mutable and immutable collection types, as such, since all objects in Swift can be declared with either var or let.

Arrays

Arrays are zero-based, and look like this:

let myArr = [21, 22, 23] 

They are equipped with a pretty standard set of methods, such as count and accessor methods...

Value and reference types

The basic data types of Swift, such as Int, Double, and Bool, are said to be value types. This means that, when passing a value to a function (including assignment of variables and constants), it is copied into its new location:

var x1 = 1 
var y1 = x1
y1 = 2
x1 == 1 // true

However, this concept extends to String, Array, Dictionary, and many other objects that, in some languages, notably Objective C, are passed by reference. Passing by reference means that we pass a pointer to the actual object itself, as an argument, rather than just copy its value:

var referenceObject1 = someValue 
var referenceObject2 = referenceObject1
referenceObject2 = someNewValue

These two variables now point to the same instance.

While this pattern is frequently desirable, it does leave a lot of variables sharing the same data--if you change one, you change the others. And that's a great source of bugs...

Variables and types


We can declare variables as follows:

var a: Int = 1

In the preceding line of code, a is declared to be of type Int, with a value of 1. Since only an Int can be assigned the value 1, Swift can automatically infer the type of a, and it is not necessary to explicitly include the type information in the variable declaration:

var a = 1

In the preceding code, it is equally clear to both Swift and the reader what type a belongs to.

Note

What, no semicolons?You can add them if you want to, and you'll have to if you want to put two statements on the same line (why would you do that?). But no, semicolons belong to C and its descendants, and despite its many similarities to that particular family of languages, Swift has left the nest.

The value of a var can be changed by simply assigning to it a new value:

var a = 1 
a = 2 

However, in Swift, we can also declare a constant, which is immutable, using the let keyword:

let b = 2 

The value of b is now set permanently. The following attempt to...

Comments


Swift has adopted C-style comments of both forms:

// We have used this one already 
// in previous sections of this chapter 

When it starts to get messy, with // at the beginning of each commented line, we have the following multiline comments:

/* 
This is a multiline 
comment, for those times when 
you just can't say it 
in a few words 
*/ 

Unlike some languages, you can nest these comments, which is handy if you need to comment out a large section of code that itself contains comments:

/* 
Comments can be nested, 
/* 
like this one 
*/ 
which can be helpful. 
*/ 

Arrays, dictionaries, and sets


Swift offers a comprehensive set of collection types, as one would expect. In common with many other languages, each of these collection types will only hold values of the same type. Thus, the type of an Array of Int values is distinct from the type of an Array of Float values, for example. If you're coming from Objective C, you may quickly come to appreciate the type safety and simplicity of Swift Array objects over NSArray.

There are no separate mutable and immutable collection types, as such, since all objects in Swift can be declared with either var or let.

Arrays

Arrays are zero-based, and look like this:

let myArr = [21, 22, 23] 

They are equipped with a pretty standard set of methods, such as count and accessor methods:

let count = myArr.count // 3 
let secondElmt = myArr[1] // 22 
let firstElmt = myArr.first // 21 
let lastElmt = myArr.last // 23 

Elements are set, logically enough, as follows:

myArr[1] = 100 

They are a lot more convenient to work with than...

Value and reference types


The basic data types of Swift, such as Int, Double, and Bool, are said to be value types. This means that, when passing a value to a function (including assignment of variables and constants), it is copied into its new location:

var x1 = 1 
var y1 = x1 
y1 = 2 
x1 == 1 // true 

However, this concept extends to String, Array, Dictionary, and many other objects that, in some languages, notably Objective C, are passed by reference. Passing by reference means that we pass a pointer to the actual object itself, as an argument, rather than just copy its value:

var referenceObject1 = someValue 
var referenceObject2 = referenceObject1 
referenceObject2 = someNewValue 

These two variables now point to the same instance.

While this pattern is frequently desirable, it does leave a lot of variables sharing the same data--if you change one, you change the others. And that's a great source of bugs.

So, in Swift, we have many more value types than reference types. This even extends...

Operators


We will take a quick tour of the most common operators in Swift, leaving such esoteric topics as custom operators for Chapter 5, Advanced Swift.

Mathematical operators

The five basic math operators will need no explanation here:

-  
+  
*  
/ 
% 

They are so-called infix operators, meaning that they are placed between their two operands:

let x = (a * a) + (b * b) 

The usual rules of precedence apply.

Augmented assignment

As in many other C-derived languages, we can replace:

x = x + 1 

With:

x += 1 

There are versions of this for the other mathematical operators:

 -= *= /= %= 

Readers should already be familiar with all these operators.

Note

There is no ++ or -- operator in Swift 3. Older versions of the language did, in fact, retain these from the C family of languages, so don't be too surprised if you come across it in older posts on the Web. If you do need to do an i++ or i-- (although for loops make these operators largely unnecessary), use i += 1 or i -= 1.

Comparison operators

Swift's comparison...

Structs, classes, and other data structures


Ways of defining and handling structured data are an important part of any programming language that supports object-oriented programming. Swift has extended the patterns typical of Objective C, Java, and the like, to include structures that are passed by value, called structs, and those that are passed by reference, called classes (see Value and reference types in this chapter). There is also the much lighter-weight tuple, which offers a kind of bridge between data structures and collection types such as dictionaries.

As well as the fact that structs are value types and classes are reference types, there are a few other points of departure, but the two structures have a lot more similarities than they do differences.

Structs

A Swift struct is basically a group of data, organized into properties, as well as methods that do something to or with those properties. There is more to come, but we'll start there for the sake of simplicity.

Let's set up a...

Enumerations


Swift offers another valuable structure, the Enum. While enumerations are a common feature of programming languages, Swift's Enum offers very much more than a simple mapping of integer values to labels.

Firstly, in cases where there is no logical mapping of Enum values to integers (or values of any other type), we can declare an Enum to be a type in its own right:

enum Color 
{ 
    case red 
    case amber 
    case green 
} 

So, here we have a case in which it would be nonsensical to map colors to integers. Swift will not allow us to try to derive some integer value from Color.red, either.

Note that the Enum name is capitalized, whereas a case is written in lowercase.

Note

This was not the case (no pun intended) in previous versions of Swift--another thing to be wary of when reading older posts, tutorials, and documentation.

There are, however, frequent uses for an Enum that do correspond to some underlying value, and Swift lets us do this, too:

enum Medal: Int 
{ 
    case gold ...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn to harness the power of macOS with the elegance of the Swift programming language
  • Become highly competent in building apps on the macOS platform
  • Get the most in-depth guide with a hands-on approach on the latest version of macOS

Description

macOS continues to lead the way in desktop operating systems, with its tight integration across the Apple ecosystem of platforms and devices. With this book, you will get an in-depth knowledge of working on macOS, enabling you to unleash the full potential of the latest version using Swift 3 to build applications. This book will help you broaden your horizons by taking your programming skills to next level. The initial chapters will show you all about the environment that surrounds a developer at the start of a project. It introduces you to the new features that Swift 3 and Xcode 8 offers and also covers the common design patterns that you need to know for planning anything more than trivial projects. You will then learn the advanced Swift programming concepts, including memory management, generics, protocol orientated and functional programming and with this knowledge you will be able to tackle the next several chapters that deal with Apple’s own Cocoa frameworks. It also covers AppKit, Foundation, and Core Data in detail which is a part of the Cocoa umbrella framework. The rest of the book will cover the challenges posed by asynchronous programming, error handling, debugging, and many other areas that are an indispensable part of producing software in a professional environment. By the end of this book, you will be well acquainted with Swift, Cocoa, and AppKit, as well as a plethora of other essential tools, and you will be ready to tackle much more complex and advanced software projects.

Who is this book for?

This book is for developers who have some experience with macOS and want to take their skills to next level by unlocking the full potential of latest version of macOS with Swift 3 to build impressive applications. Basic knowledge of Swift will be beneficial but is not required.

What you will learn

  • Combine beautiful design with robust code for the very best user experience
  • Bring the best coding practices to the new macOS Sierra
  • See what's new in Swift 3.0 and how best to leverage the Swift language
  • Master Apple's tools, including Xcode, Interface Builder, and Instruments
  • Use Unix and other common command-line tools to increase productivity
  • Explore the essential Cocoa frameworks, including networking, animation, audio, and video

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 31, 2017
Length: 626 pages
Edition : 1st
Language : English
ISBN-13 : 9781786461698
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 : May 31, 2017
Length: 626 pages
Edition : 1st
Language : English
ISBN-13 : 9781786461698
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 $ 97.98
Mastering macOS Programming
$48.99
Swift 4 Programming Cookbook
$48.99
Total $ 97.98 Stars icon
Banner background image

Table of Contents

20 Chapters
Hello macOS Chevron down icon Chevron up icon
Basic Swift Chevron down icon Chevron up icon
Checking Out the Power of Xcode Chevron down icon Chevron up icon
MVC and Other Design Patterns Chevron down icon Chevron up icon
Advanced Swift Chevron down icon Chevron up icon
Cocoa Frameworks - The Backbone of Your Apps Chevron down icon Chevron up icon
Creating Views Programmatically Chevron down icon Chevron up icon
Strings and Text Chevron down icon Chevron up icon
Getting More from Interface Builder Chevron down icon Chevron up icon
Drawing on the Strength of Core Graphics Chevron down icon Chevron up icon
Core Animation Chevron down icon Chevron up icon
Handling Errors Gracefully Chevron down icon Chevron up icon
Persistent Storage Chevron down icon Chevron up icon
The Benefits of Core Data Chevron down icon Chevron up icon
Connect to the World - Networking Chevron down icon Chevron up icon
Concurrency and Asynchronous Programming Chevron down icon Chevron up icon
Understanding Xcodes Debugging Tools Chevron down icon Chevron up icon
LLDB and the Command Line Chevron down icon Chevron up icon
Deploying Third - Party Code Chevron down icon Chevron up icon
Wrapping It Up Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2
(6 Ratings)
5 star 33.3%
4 star 16.7%
3 star 16.7%
2 star 0%
1 star 33.3%
Filter icon Filter
Top Reviews

Filter reviews by




howld May 10, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great tutorial and very easy understand to understand the concept
Amazon Verified review Amazon
Sorin Dolha Dec 15, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I love this book. It's generally up to date (as of December 2017), the author has a nice style of not presenting everything and letting the reader also think a bit, and often offers - besides the general topics - tricks that I find interesting and useful.
Amazon Verified review Amazon
Amazon Customer May 22, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
very good
Amazon Verified review Amazon
Jim McCoy Apr 04, 2022
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Lots of typos and it appears the errata is no longer available. Could really use an update. I like the prose and the somewhat lighthearted style. Helps keep things interesting.
Amazon Verified review Amazon
Amazon Customer May 16, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
I'm sure this was a great book when it first came out but the current version of swift and xcode does not work with the tutorials cover. spent hours trying to get the first project (sales tax calculator) to work and never could, had a programmer friend look into it, and they said it was because the version of swift being covered in the book is obsolete
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.