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
$27.98 $39.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2 (6 Ratings)
eBook 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
$27.98 $39.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2 (6 Ratings)
eBook 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 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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 : 9781786467591
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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : May 31, 2017
Length: 626 pages
Edition : 1st
Language : English
ISBN-13 : 9781786467591
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

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.