Supports Xcode 6.3
A Practical Guide to Building Your First App from Scratch
Beginning
iOS 8 Programming with Swift SIMON NG
APPCODA
Copyright © 2015 AppCoda Limited All rights reserved. Please do not distribute or share without permission. No part of this book or corresponding materials (such as images or source code) may be distributed by any means without prior written permission of the author. All trademarks and registered trademarks appearing in this book are the property of their respective owners. i
Swift Playgrounds
In this year’s Worldwide Developer Conference, Apple surprised all iOS developers by launching a new programming language called Swift. Swift is advertised as a “fast, modern, safe, interactive” programming language. The language is easier to learn and comes with features to make programming more productive. Prior to the announcement of Swift, iOS apps were primarily written in Objective-C. The language has been around for more than 20 years and was chosen by Apple as the primary programming language for Mac and iOS development. I’ve talked to many aspiring iOS developers. A majority of them said Objective-C was hard to learn and its syntax looked weird. Simply put, the code scares some beginners o " from learning iOS programming.
x
The release of Swift programming language is probably Apple’s answer to some of these comments. The syntax is much cleaner and easier to read. I have been programming in Swift since its beta release. I can say you're almost guaranteed to be more productive using Swift. It definitely speeds up the development process. Once you get used to Swift programming, it would be hard for you to switch back to Objective-C. It seems to me that Swift will lure more web developers to build apps. If you’re a web developer with some programming experience on any scripting languages, you can leverage your existing expertise to gain knowledge on developing on iOS. It would be fairly easy for you to pick up Swift. That said, even if you’re a total beginner with no prior programming experience, you’ll also find the language friendlier and feel more comfortable to develop apps in Swift. To get a taste of Swift programming language, let’s take a look at the following code snippets. Objective-C const int count = 10; double price = 23.55; NSString *firstMessage = @"Swift is awesome. "; NSString *secondMessage = @"What do you think?"; NSString *message = [NSString stringWithFormat:@"%@%@", firstMessage, secondMessage]; NSLog(@"%@", message);
Swift let count = 10 var price = 23.55 let firstMessage = "Swift is awesome. " let secondMessage= "What do you think?" var message = firstMessage + secondMessage println(message)
The first block of code is written in Objective-C, while the second one is written in Swift. Which language do you prefer? I guess you would prefer to programming in Swift, especially if you’re frustrated with the Objective-C syntax.
xi
Constants and variables are two basic elements in programming. In the Objective-C world, it’s your responsibility to specify the type information when declaring a variable or a constant, be it an integer or a string. For Swift, it introduces a new feature called Type Inference. You no longer need to annotate variables/constants with type information. All you need to do is to use let to declare a constant and
var to
declare a variable. Swift is
intelligent enough to deduce the type by examining the values you provide. Another di"erence that you may notice is the omission of the semi-colon. In Objective-C, you have to end each statement with a semicolon. If you forget to do so, you will end up with an error. I know many Objective-C beginners have experienced this error before. Swift should make your developer’s life easier. Swift has added many powerful features to streamline your coding. As you can see from the above example, string manipulation is much simpler. In Objective-C, you have to choose between NSString and NSMutableString classes to indicate whether the string can be modified. You do not need to make such choice in Swift. Whenever you assign a string as variable (i.e. var), the string can be modified in your code. Concatenating strings is super easy. Just use the + operator to combine two strings. Further, Swift allows you to compare strings directly using the == operator. There is no better way to explore coding than actually writing code. Xcode 6 introduces a new feature called Playgrounds. It’s an interactive development environment for developers to experiment Swift programming and allows you to see the result of your code in real-time. Assuming you’ve installed Xcode 6 (or up), launch the application (by clicking the Xcode icon in Launchpad). You’ll see a startup dialog.
xii
Playground is a special type of Xcode file. You can simply click “Get started with a playground” to get started. You’ll then be prompted to fill in a project name and select a platform.
Use the default name or your own name but remember to select iOS as the platform. Once you confirm to save the file, Xcode opens the Playground interface. Your screen should like this:
xiii
On the left pane of the screen, it is the editor area where you type your code. As you write your code, Playground immediately interprets your code and displays the result on the right pane. By default, Playground includes two lines of code. As you can see, the result of the “str” declaration appears immediately on the right pane. We’ll write some code in Playground together. Remember the purpose of this exercise is to let you experience Swift programming and get a better idea of Xcode 6. I’ll try to explain part of the code as we move along. However, even if you do not understand any line of the code, that is completely fine especially you’re a new comer. I’m quite sure you’ll be confused by some of the terms like class, method. Forget about their meanings, just relax and play around with Xcode. We’ll go over them again in later chapters. Cool! Let’s get started. First, key in a couple lines of code. Here we declare two more variables: var message1 = "Hello Swift! How can I get started?" var message2 = "The best way to get started is to stop talking and code."
As soon as you insert the above lines of code, you will see the result on the right pane.
Let’s continue to add the following line of code: message1.uppercaseString
xiv
Xcode’s editor comes with an auto-complete feature. Auto-complete is a very handy feature to speed up your coding. Once you type “mess”, you’ll see an auto-complete window showing some suggestions based on what you have keyed in. All you need to do is to select “message1” and hit enter.
Swift employs the dot syntax for calling methods and accessing the properties of a variable. As you type the dot after message1, the auto-complete window pops out again. It suggests a list of methods and properties belonged to the variable. You can continue to type “uppercaseString” or select it from the auto-complete window.
xv
Once you complete your typing, you would see the output immediately. When we use the uppercaseString property, the content of message1 is converted to upper case automatically. Continue to type the following line of code: message2.lowercaseString + " Okay, I'm working on it "
Swift allows you to concatenate two strings with the + operator. The line of code converts the content of message2 into lower case and then concatenated with another string. Interestingly, you can include emoji characters in your code. You may wonder how to type emoji characters in Mac OS. It’s easy. Just press control-command-spacebar and an emoji picker will be displayed. Let’s continue to type the following code snippet: if message1 == message2 { println("Same message") } else { println("Not the same message") }
Conditional logic is very common in programming. Sometimes, you want to execute certain part of code only when a certain condition is met. An if-else statement is one of the ways in Swift to control program flow. Here we compare the content of message1 and message2 variables using the == operator. If they’re equal, the program prints “Same message”. Otherwise, it prints “Not the same message”. You should see the following result on your screen.
Let’s have some more fun and create a label, which is a common user interface element:
xvi
let messageLabel = UILabel(frame: CGRectMake(0, 0, 300, 50)) messageLabel.text = message1 messageLabel
Here we use a built-in UILabel class to create a label and set its size to 300x50 points. We then set its text to message1. To preview a UI element in Playground, you can click the Quick Look or Value History icon. The Quick Look feature displays the label as a pop-over. If you use the Value History feature, Playground opens a separate preview pane.
It’s just a plain label. Wouldn’t be great if you can change its color? Even better, you just need one line of code to customize the color. What’s more you can easily center the text and change the label to round corner. Type the following lines and you’ll see a rounded corner label with orange background. messageLabel.backgroundColor = UIColor.orangeColor() messageLabel.textAlignment = NSTextAlignment.Center messageLabel.layer.cornerRadius = 10.0 messageLabel.clipsToBounds = true messageLabel
This is the power of iOS SDK. It comes with tons of pre-built elements and allows developers to customize them with few lines of code.
xvii
Don’t get me wrong. Typically you do not need to write code to create the user interface. Xcode provides a Storyboard feature that lets you design UI using drag-and-drop. We’ll go through in the next chapter. So you’ve got a taste of Swift? What do you think? Love it? I hope you find Swift a lot easier to learn and code. Most importantly, I hope it don’t scare you away from learning app development. Next up, you’ll learn how to build your first app. For your reference, you can download the Playground file from https://www.dropbox.com/ s/y9plgddbsjauhqq/MyPlayground.zip?dl=0.
xviii