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
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Application Development with Swift
Application Development with Swift

Application Development with Swift: Develop highly efficient and appealing iOS applications by using the Swift language

eBook
$9.99 $29.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
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
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Application Development with Swift

Chapter 1. Hello Swift

Welcome to the developing applications with Swift book. It's my pleasure to talk about iOS development and Swift. This book assumes that you have some basic experience in iOS development, and a little experience of using Swift. If you don't have any experience of Swift, don't worry, just go ahead with us and be prepared to master the iOS development using Swift. I believe in learning by example methodology and, starting from Chapter 3, Touch ID, we will introduce the new technology of iOS 8, and write a simple demo on it using Swift.

In this chapter, we will talk about the Swift programming language, and get our hands dirty with Swift. If you are familiar with Swift, you can either skip this chapter, or you can review your Swift knowledge. We will talk about the Swift language and its features, and how to try it using Playgrounds in Xcode 6. Playground is a new, awesome, and innovative feature that allows you to try any piece of code, and see the results without explicitly running, or even compiling your code. You will become familiar with the code structure, and some important data types such as arrays, dictionaries, and so on.

Introduction to Swift

Swift is a new (Apple has open sourced it!), scripting, programming language for developing apps for iOS, OS X, and watchOS. Apple has introduced this language to make things easier and fun. Unlike Objective-C, Swift is not a superset of C programming language. But believe me, it has the power of both C and Objective-C.

It's the first time we have an alternative to Objective-C, since Apple introduced iOS and OSX development tools. As a new programming language, Swift introduces many new features and concepts that did not exist in Objective-C, and we will talk about them in next sections. For Objective-C developers, Swift will be familiar to them, as it adopts the readability of Objective-C's named parameters. Swift is a friendly programming language. It is so expressive and funny even for new programmers who have no experience with Objective-C.

Like Objective-C, Swift is an OOP language and you can easily create classes, objects, methods, and properties. Swift is built to make developers write safe code, and you will feel this when you will start working with it. An example of this is that you can't use variables without initialization. Swift saves you from making silly errors that you could make, such as using variables before initialization.

Don't hesitate to work with Swift, and give it a shot. Swift co-exists alongside your existing Objective-C code, and is easy to work with. You can also replace your existing Objective-C code with Swift, or start your project from scratch with Swift as your primary development language.

Make sure that you are familiar with Swift features to feel its power, and enjoy it. Some of these features are new for Objective-C developers, and these will let you love Swift, as I do:

  • Closures
  • Tuples
  • Range operators
  • Generics
  • Structures
  • Functional programming patterns

Playgrounds

We mentioned the Playground feature earlier—it is a new innovative feature supported in Xcode 6 and higher. It gives you the ability to try any piece of code in Swift, and see the results immediately without the need to compile or run the code. So, imagine that you are learning Swift, or working in a project with Swift, and you need to try some code, and check its result. If you are in Objective-C, you need to create a new project, write the code, build, run, and open the simulator to see the results! Very time consuming, isn't it? I mean, it's time consuming here, in the learning track, but after you master the language, you don't need to use Playgrounds. You may just need to use it in test or to check something. To play with the Playground feature use the following steps:

  1. In Swift and Xcode 6, or higher, just create a new playground (as shown in the following screenshot) or open an existing one by choosing the .playground file in a navigator:
    Playgrounds
  2. Now, enter Swift code in the .playground file, and enjoy the results in the right-hand side sidebar. Xcode evaluates your code while you type it, and for each statement, Xcode displays the results of it in the right-hand side sidebar.
    Playgrounds

As you see, each line of code is examined, and its result is shown in the results sidebar, in the right-hand side. Even the for loop statement shows you how many times the entire code was executed. To see the value of any variable, just write it in a separate line, and check its value in the right-hand side sidebar. (Check line 11 in the preceding screenshot).

Another feature of Playground is the value history. In the previous for loop, we have a piece of code that is executed repeatedly, right? But I want to know what is going on in each iteration. Xcode helps you with this by providing the history button in the results sidebar, on the line containing the number of times. Once you click on it, it displays a complete graph (timeline) for the values over the time. In the graph, x axis represents time, and y axis represents the value at this time (this iteration).

Once you click on the circle in the results view, you can see the value of this iteration:

Playgrounds

Also, keep in mind that Playground includes the standard editing features of Xcode, such as code completion, error checking, syntax correction, and suggestions.

The code structure

Before starting to write Swift, you have to be aware of its structure, as it is a very important thing to know in any programming language.

As we said earlier, Swift is not a superset of C. For sure it's influenced by C and Objective-C but easier and fun to use than both.

I will share with you a piece of code in Swift to show its structure:

import UIKit

let pi = 3.14
//Display all even numbers from 0 to 10
for i in 0...10
{
    if i % 2 == 0
    {
        println("\(i) is even")
    }
}

func sayHello(name: String = "there")
{
    
    println("Hello \(name)")
}

sayHello(name: "John") // will print "Hello John" 
sayHello() //Will print "Hello there", based on default value

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed direct to you.

If you check this code, you will find that we don't use semicolons. This is because in Swift they are optional. However, compiler will not complain if you do use them. The only area where semicolons are required is when you write multiple statements in the same line.

In Swift, you use var for variables, and let for constants; but this doesn't mean that Swift is not a typed language. The compiler, based on the initial value, identifies the type implicitly. But in some cases, you have to write the type if you don't set an initial value; or the initial value is not sufficient to identify the type.

Consider the following code for example:

var count = 5
var msg : String
var total : Double = 0

In this code, the count variable is of the Int type, because its initial value is in integer. In the msg variable, we didn't set an initial value, so we will have to explicitly write the type of the msg variable. The same is applicable for total; we need it to be of the Double type but as its initial value is not sufficient, the compiler will consider it as Int.

In Swift, you will see that there is no main function to start with, as the code written in the global scope is considered as the start of your program. So, you can imagine that a single line of code in Swift can be considered as a program!

The last thing I want to mention is that curly braces are very important in Swift, as they are mandatory in any control flow statements, such as if, while, and so on.

Arrays

An array is every developer's best friend and saves the collection of data in an ordered list. In Swift, an array is very easy to use and contains many helpful methods for use. Before exploring it, we have to clarify some important points.

Array by default is mutable so that it accepts adding, changing, or removing items from it, except if we define it as a constant, using let. In this case, it will be immutable, as it becomes constant.

In Objective-C, you can save any type of object, and you won't have to specify any information about their type. In Swift, arrays are typed; this means that the type of item should be clear, and all the items should be of the same type. The type can be defined explicitly, or it can be inferred.

An array doesn't have to be of a class type. So, you can create an array of Int, and in such a case, you can't insert any other value than the Int type.

The following are examples to make these points clear:

let languages = ["Arabic", "English", "French"]
//Here type is inferred as String, So this Array is of type String
//Also this array is immutable as it defined as let

var primes :[Int] = [2, 3, 5, 7, 11]
//Type is written explicitly

primes.append(13) //mutable array as it defined as var

Initializing an array

To initialize and create an array, you can use the previous ways with initial values, or you can either create it empty, or by using repeating values:

Initializing an array

As you see in the example, it's very easy to initialize empty arrays, or arrays with repeating values. Swift also provides a great feature to append two arrays that result in a new array.

Iterating over arrays

The explanation is not complete without mentioning how to iterate over an array. Actually, iterating over an array in Swift is very easy and straightforward. To iterate over values of an array, you will use the for-in loop like this:

var seasons = ["Winter", "Spring", "Summer", "Autumn"]

for season in seasons{
    println(season)
}
/*
Winter
Spring
Summer
Autumn
*/

And if you want the index of the value in each iteration, you can use the enumerate method. In each iteration, the method returns a tuple that is composed of an index and value of each item in the array. Check the next example to make things clear:

for (index, season) in enumerate(seasons){
    
    println("Season #\(index + 1) is \(season)")
}
/*
Season #1 is Winter
Season #2 is Spring
Season #3 is Summer
Season #4 is Autumn
*/

For all those who don't know tuples, tuples in Swift are used to create and pass around a group of values. It can be used to return multiple values from a function in a single group.

Appending items

You can append items easily by using the append method, which appends an item at the end of an array. To append multiple items at once, append an array of these items.

You can also use the insert method that inserts items at a specific location.

var nums = [1, 3]            // [1, 3]
nums.append(4)              //  [1, 3, 4]
nums.insert(5, atIndex: 1) //   [1, 5, 3, 4]
nums += [10, 11]          //    [1, 5, 3, 4, 10, 11]

Removing and updating items

An array has a built-in removeAtIndex function to remove an item at the index and a removeLast function to remove the last item. These functions are awesome. While you call them, they return the deleted item at the same time and thus, you don't have to write another line of code to grab the item before deleting it.

nums.removeAtIndex(1) // return 5
nums.removeLast()    //  return 11
nums                //   [1, 3, 4, 10]
nums[0...2] = []   //    array now is [10]

In this code we removed an item at index 1 and the last item, as you see in the first two lines.

Another great feature in Swift is using ranges, which we used for replacing the items in the range from 0-2. This replaces the first three items with an empty array. That means the first three items have been removed. You can also replace it with an array containing data. Now, replace the items in the range with the items in the array. The most important thing is to be careful with the ranges that are used, and make sure that they are an inbound of the array. The out of bound ranges will throw exceptions.

Dictionaries

Dictionaries in Swift are like arrays in special characteristics, such as mutable and strongly typed. Dictionary is mutable by default, except if used with let. Also keys and values should be of the same type.

The dictionary type is inferred by the initial values, or you can explicitly write it using the square brackets [keyType, valueType].

Initializing a dictionary

To initialize a dictionary, you have two options. The first option is to create an empty one with no data. You can create it like this:

var dic1 = [String:Int]() // 0 key/value pairs

As we see in this case, we had to explicitly write the type of keys and values.

In the second option, you have the predefined values like this:

var dic2 = ["EN" : "English", "FR" : "French"]
//["EN": "English", "FR": "French"]

Here we didn't write the type of keys or the values, as it was inferred from the initial values.

Appending or updating values

Updating or appending a value with a key in a dictionary is very similar, and can be done like this:

dic2["AR"] = "Arabic" //Add
dic2["EN"] = "ENGLISH" //update
//["EN": "ENGLISH", "FR": "French", "AR": "Arabic"]

As you can see, in the first line it will create a new record in the dictionary, because the "AR" key did not exist before. In the second line as the "EN" key exists, it will update each of its values with the given one. Very simple right!

Another method to update a value for the key in the dictionary is to call updateValue(val, forKey:). Take a look at the following example:

dic2.updateValue("ARABIC", forKey: "AR") //returns "Arabic"
//dic2 now is ["EN": "ENGLISH", "FR": "French", "AR": "ARABIC"]

As you see in the code, this method returns the old value after updating the new value. So, if you want to retrieve the old value after the update function is done, this method is the best choice.

Removing items from the dictionary

This is the same as updating values. You have two ways to remove items from dictionary. The first is to set the value of the key as nil, and the second is to call the removeValueForKey(key) method. This method also returns the old value before deleting it.

dic2["AR"] = nil
dic2.removeValueForKey("FR") //returns French
//["EN": "ENGLISH"]
dic2["FR"]  // Returns nil

Enum

Enumeration is a very useful concept that is used to group related values together and define a new type for them. You must be familiar with enumeration in Objective-C or in C. Swift added new flavors to enum, and made it more flexible and easy to use.

To create enum in Swift, use the enum keyword, and then you can list all the possible cases after the case keyword:

enum LevelDifficulty{
    case Easy
    case Medium
    case Hard
    case Advanced
}

In the preceding code, we defined the new type as LevelDifficulty to group the related values of difficulties together (Easy, Medium, Hard, and Advanced). To use this enum, you can easily create variables with the LevelDifficulty type:

var easyMode = LevelDifficulty.Easy
//Type is inferred as LevelDifficulty

var mode : LevelDifficulty
mode = .Hard

As we see in this example, there are various ways to create enum. In the second one, for the variable mode, we set the type first, and then gave it a value. To set the value of a variable, we use a . (dot) operator.

Using enumerations with the switch statement

Swift makes life easy with enum. We can see this in the following example:

var power :Int
switch mode
{
case .Easy:
    power = 20
case .Medium:
    power = 30
case .Hard:
    power = 50
case .Advanced:
    power = 90
}

Very easy, isn't it? But take care of some the very important notes in the switch statement while using it in Swift:

  • It has to be exhaustive, which means that you have to cover all the possible values of enum, and list them as cases, or use the default case.
  • Swift doesn't support fallthrough. Unlike other languages, Swift doesn't fall through the bottom of each switch case into the next one. The switch statement finishes its execution as soon as a switch case is matched without explicitly writing a break statement. For sure, this makes your code safer by avoiding the execution of more than one switch case, by forgetting to add a break statement!

Enumerations with associated values

Swift gives enumerations another flavor and a great feature. This enables you to store the additional information for each member value. These associated values can be any given type, and can also be different for each member value. If you feel confused, look at the next example:

enum MissionState{
    case Accomplished(Int)
    case Attempted(String, Int)
    case UnAttempted
}

In this enum, in the case of Accomplished, we provide an integer value for it, which will represent the number of stars earned in this mission. In the case of Attempted, we provide two values for it. One is the string that represents the most progress achieved, and the other is the integer value for the number of attempts. The last one is UnAttempted, where we don't have to provide any additional information.

So now, let's see how to use this type of enumerations:

var state = MissionState.Accomplished(3)
var attemptState = MissionState.Attempted("80%", 3)

It is very easy to use this type of enumeration in the switch statement:

switch attemptState
{
case .Accomplished(let stars):
    println("Mission accomplished with \(stars) stars")
case .Attempted(let progress, let count):
    println("Mission attempted \(count) times with most progress \(progress)")
case .UnAttempted:
    println("UnAttempted")
}

To use the associated values in enumerations, Swift gives you the ability to label or describe these different values. This will make your code more readable and easy to use. To recreate our previous enum with labels, use the following code:

enum MissionState{
    case Accomplished(stars:Int)
    case Attempted(missionProgress:String, attemptsCount:Int)
    case UnAttempted
}

var state = MissionState.Accomplished(stars:3)
var attemptState = MissionState.Attempted(missionProgress: "80%", attemptsCount: 3)

You can see how the labels make the code very understandable and easier to read.

Functions

In Swift, it's very easy to create the functions using the func keyword, followed by the function name and parameters between the parentheses. Parentheses are required even if the function doesn't take parameters. So we will use parentheses without writing anything in between. For some other languages we need to use the void keyword for the function that doesn't take parameters. Parameters are comma separated and each one is combined with two items: the name and the type of parameters, separated by : (colon). Check this example of a simple function:

func sayHi(name:String)
{
    println("Hi \(name)")
}

sayHi("John") //Hi John

One of the great features that I love in Objective-C is that you can write a full description for each parameter in methods, which helps everyone, working in the project, to understand the code. The same is here in Swift; you can label parameters more easily. To do so, just type the name (description) before the parameter, or add # before the name of parameter, if the name is sufficient as a description and meaningful. Check these two examples:

func joinStrings(string1 str1:String, toString str2:String, joinWith j:String)
{
    println(str1 + j + str2)
}

joinStrings(string1: "John", toString: "Smith", joinWith: ",") //"John,Smith"

func joinStrings2(#string1:String, #toString:String, #glue:String)
{
    println(string1 + glue + toString)
}

joinStrings2(string1: "John", toString: "Deo",glue: "/") //"John/Deo"

As we saw in the first method, we wrote the description for each parameter, so that the code would be readable and understandable. In the second one, the parameter names were self-explained, and they needed no explanation. In such a case, we just added # before them, and then the compiler treated them as labels for parameters.

Like any function in any language, Swift may return results after the execution. Functions can return multiple values and not just a value like Objective-C, thanks to tuples! To do this, just write -> after the parentheses, and then add a tuple that describes the results:

func getMaxAndSum(arr:[Int]) -> (max:Int, sum:Int)
{
    var max = Int.min
    var sum = 0
    for num in arr{
        if num > max
        {
            max = num
        }
        sum += num
    }
    return(max, sum)
}

let result = getMaxAndSum([10, 20, 5])
result.max //20
result.sum //35

Closures

Think of closures as a piece of code or functionality to pass around in your code. Closures in Swift are very similar to blocks in C and Objective-C. Closures in Swift are the first class type and it is allowed to be returned or passed as a parameter. And as we will see, functions are just special instances of closures. The general formula for closures is like this:

{ (params) -> returnType in
    
    //statements
}

As you can see, we opened curly braces, and then we added the necessary parameters followed by the return type and the in keyword. Knowing this formula will help you a lot in using closures, and you will not feel any frustration using it.

This is an example of using closures in sorting the collection of data:

var nums = [10, 3, 20, 40, 1, 5, 11]
sorted(nums, { (number1, number2) -> Bool in
    return number1 > number2
})
//[40, 20, 11, 10, 5, 3, 1]

Here, the closure is used to identify the comparison result of any two numbers. As we saw, the closure takes two parameters and returns a Boolean, that is the result of the comparison.

Summary

In this chapter, we saw what Swift is, and how the code structure works. We saw its new features by using arrays, dictionaries, functions, and closures. We also learned how to use Playground to try any piece of code in Swift anytime, without creating a new project, or even compiling and building your project. At the end of this chapter, you have the basic skills to write Swift code. In the next chapter, we will talk about some advanced features in Swift, including casting and checking, protocols, delegation, generics, memory management, and much more. Stay tuned!

Left arrow icon Right arrow icon
Download code icon Download Code

Description

After years of using Objective-C for developing apps for iOS/Mac OS, Apple now offers a new, creative, easy, and innovative programming language for application development, called Swift. Swift makes iOS application development a breeze by offering speed, security and power to your application development process. Swift is easy to learn and has awesome features such as being open source, debugging,interactive playgrounds, error handling model, and so on. Swift has simplified its memory management with Automatic Reference Counting (ARC) and it is compatible with Objective-C. This book has been created to provide you with the information and skills you need to use the new programming language Swift. The book starts with an introduction to Swift and code structure. Following this, you will use playgrounds to become familiar with the language in no time. Then the book takes you through the advanced features offered by Swift and how to use them with your old Objective-C code or projects. You will then learn to use Swift in real projects by covering APIs such as HealthKit, Metal, WatchKit, and Touch ID in each chapter. The book's easy to follow structure ensures you get the best start to developing applications with Swift.

Who is this book for?

If you are an iOS developer with experience in Objective-C, and wish to develop applications with Swift, then this book is ideal for you. Familiarity with the fundamentals of Swift is an added advantage but not a necessity.
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 28, 2015
Length: 144 pages
Edition : 1st
Language : English
ISBN-13 : 9781785288173
Vendor :
Apple
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
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
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Aug 28, 2015
Length: 144 pages
Edition : 1st
Language : English
ISBN-13 : 9781785288173
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 $ 114.97
Application Development with Swift
$38.99
Swift 2 Design Patterns
$26.99
Swift 2 Blueprints
$48.99
Total $ 114.97 Stars icon

Table of Contents

8 Chapters
1. Hello Swift Chevron down icon Chevron up icon
2. Advanced Swift Chevron down icon Chevron up icon
3. Touch ID Chevron down icon Chevron up icon
4. Introduction to HealthKit Chevron down icon Chevron up icon
5. Introduction to Metal Chevron down icon Chevron up icon
6. Introduction to WatchKit Chevron down icon Chevron up icon
7. Swift App Extensions Chevron down icon Chevron up icon
Index 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.6
(5 Ratings)
5 star 80%
4 star 0%
3 star 20%
2 star 0%
1 star 0%
ahmed May 20, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you're looking to make an iOS app, and you want to learn how to do it properly this is book the perfect foundation. The amount of detail, thought and effort put forward is apparently clear from the beginning through the end.
Amazon Verified review Amazon
Dima Oct 21, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Book’s caption looks commonly, but its content isn’t so. We wouldn’t learn Swift deeply or get approaches to make applications. And also it’s not about OS X as I guessed at first. This book is for experienced iOS developer with knowledge Objective C.You will find here a lot of useful information. At first you’ll get great Swift course, not deeply, but it’s enough to get rest of this book. Main part of book you will learn new iOS's features, such as Touch ID, HealthKit, Metal and WatchKit. All chapters goes with code examples and screenshots so you never lost. I’m not very good in English but I haven’t any problem in understanding the text.One thing made me disappointed was this book is not about OS X, caption is slightly misleading for me. But it’s OK, I need book about iOS too.Shortly, this book is great booster for your iOS developing skills.
Amazon Verified review Amazon
Winston Sep 28, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Application Development with Swift is a great book that will jumpstart iOS development for any budding developer or season objective c developer. The book starts with an thorough introduction to the Swift language by using playgrounds to practice code samples.However, this book is for an Objective C developer. The book shows Objective-C developers how to refactor their code for Swift. MUST BUY!!!
Amazon Verified review Amazon
SuJo Nov 05, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was looking for a book to work with the new Apple Watch, and I decided to give this a try. The information in the book was accurate and easy to follow along. I'm a complete beginner but I do have a background in C++, so the code flow was easy to pick up on and I was up and running in no time at all. I felt the book did what it set out to do, it got me acquainted with Swift. The first few chapters are great for starting out, I didn't feel overwhelmed at all. I was able to pick this book up on Packt Publishing's main site by using my Packtlib membership, it's cheaper than buying multiple books and I can pickup whenever I want.
Amazon Verified review Amazon
Scott Steinman Oct 31, 2015
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
The aim this book is to transition existing Objective-C iOS developers to Swift. Therefore, itdoes not cover the basics of iOS Cocoa Touch programming or how to use Xcode. It covers thecore of the Swift programming language — not every detail, but the important ones for anestablished programmer to begin using Swift as a replacement for Objective-C.One major problem with the current edition of the book is that it uses Xcode 6 and Swift 1.2. Inthe short time since its publication, Apple has moved on to Xcode 7 and Swift 2. The sourcecode examples (when full projects are written rather than playground explorations) will notcompile with Xcode 7. Even after applying Xcode’s Swift 2 migration tool, several errors remainthat prevent compilation. When I tried to fix a few of them manually, the code crashed. Anupdated edition of this book is therefore a necessity. In addition, the book covers iOS 8 andWatchKit 1 — iOS 9 and WatchKit 2 were announced in June and are already released.In addition, while the book enumerates many of the features of Swift, paying more attention tothose not present in Objective-C, it fails to go beyond this to provide tips and tricks, or anyinsight into when and how it is best to use each feature. In this regard, its coverage of Swiftdoes not really add anything that’s not already present in Apple’s free The Swift ProgrammingLanguage eBook.Despite not covering everyday iOS programming in Swift, the book covers a few more recentadditions to iOS such as Touch ID, HealthKit, Metal, App Extensions, and interacting with theApple Watch. Each is covered tersely, and I’m not convinced that the reader could build ameaningful app using these technologies from the coverage offered by this book. Theirinclusion is puzzling to me. While established iOS programmers would need to know how toaccess these new technologies in Swift, not helping them learn how to build the bulk of theirapps or to translate the existing Objective-C Cocoa Touch code to Swift may be a disservice. Afew chapters showing how to use Swift to build a commonly-used type of iOS app would havebeen extremely helpful because it would give the reader basic insight into writing Swift code forinteracting with controls through touch and gestures, interacting with the internet, and othertasks used more commonly than Touch ID, HealthKit, Metal, App Extensions or the AppleWatch. As is, the book feels like two unrelated books — one on some differences between Swiftand Objective-C, and the other a tour of recent additions to iOS 8 — thrown together. What’smissing is what the title promises — how to create an application using Swift.A minor issue is the syntax and grammar of the text. There are many examples of awkwardgrammar, such as “…but take care of some the very important notes…”. Although this does notprevent the reader from understanding the book or grasping the concepts from it, it does detractfrom the enjoyment of reading it a bit. The manuscript should have undergone a more thoroughproofreading by reviewers and the editor.Specific Points:Chapter 1:Chapter 1 is a rapid, minimalist review of the basics of Swift, mostly identifying where it differsfrom Objective-C. The reader would have to access another reference to learn all of the differentways that collections can be manipulated, or how enums can be applied to simplify CocoaTouch code, or how closures can be written (especially with the shortcuts that Swift allows). Twoextremely important Swift language additions, structs and optionals, are not covered at all.Many Cocoa Touch methods have optional return values. Swift iOS programming is not possiblewithout an understanding of optionals and how to unwrap them safely.It is stated that there’s no main function in Swift. That’s definitely true within the playground. Inan iOS project, the @UIApplicationMain operator instructs the compiler to generate the mainfunction for you — it’s there, but you don’t have to deal with it.The discussion of functions states that you type the name (description) before the parameter,and can add # before the name of a parameter if the name is sufficient. This description appliesthe word “name” to two different concepts — description and parameter — so it confuses whichname is sufficient and meaningful. Only by reading the code on the following page does thereader determine that the parameter’s actual name is sufficient, so the description is notneeded.Chapter 2:Chapter 2’s coverage of type casting and checking is very welcome. This topic tends to beskimmed over in other Swift books and mentioned only when first needed in an exampleprogramming. This is especially true for the distinction between as and as?. Likewise, thediscussion of the use of AnyObject vs. Any was nicely done.The coverage of protocols is thorough as it relates to Swift 1, but does not touch upon a keyfeature that has been revealed in Swift 2 — protocol-oriented programming. This is, of course,not the fault of the authors, but it is unfortunate because Apple is promoting the application ofprotocol-oriented programming as a major programming technique in future Swift code.A small point: It’s stated in the section on delegation that if a class wants to use theUITableViewDataSource and UITableViewDelegate methods, it must be a protocol of the table.More correctly stated, since a class cannot be a protocol, the class must conform to theprotocols.In the section “Adding computed properties”, extensions add computed instance properties, notcomputer instance properties.Chapter 4:When an NSSet is created to return the types of data we wish to read or write from HealthKit —the user’s height, weight and birthdate — optional versions are stored. No explanation is givenas to why optionals are needed here.Chapter 5:The author recommends that most graphics applications, other than those written by large gamecompanies, should not use Metal. Why then is Metal included as a topic in this book? I thinkthat Metal is too large a topic to cover adequately in one chapter, if the reader is to learn how towrite a simple 3D program, as 3D engines are quite complicated. An entire book could easily bedevoted to this topic alone.Does the 3D Rendering Pipeline section apply to all 3D engines (including Metal) or only toolder engines? This is not clear to me.Chapter 6:The discussion of customizing interface elements in WatchKit is a bit confusing. First, it’s statedthat you can’t do it. Then the next sentence states that you can add a custom UILabel.Afterwards, it’s stated that you can’t do that in WatchKit. In that middle sentence, should it havestated that in UIKit on iPhones and iPads, you can add a custom UILabel?Note: Groups in WatchKit seem to be analogous the UIStackViews of iOS 9. If this book hadcovered iOS 9 instead of 8, this could have been discussed.Chapter 7:While WatchKit was covered in the previous chapter, no means of communicating between aniPhone and an Apple Watch was provided as an example app. Instead, a Today widget iscreated in Chapter 7’s coverage of app extensions. A WatchKit extension would have been avery useful addition to this chapter.
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 the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
Modal Close icon
Modal Close icon