Читать книгу Beginning Swift Programming - Lee Wei-Meng - Страница 2

1
Introduction to Swift

Оглавление

WHAT YOU WILL LEARN IN THIS CHAPTER:

• What Swift is

• Why Swift is important

• Setting up the development environment to learn Swift

• How to create a Playground project

• How to create an iOS project

• The syntax of Swift

• How to declare constants

• How to declare variables

• Using string interpolation to include variable values in strings

• Swift statements

• How to print the values of variables for debugging

• How to insert comments in your Swift code

Apple surprised the Mac and iOS developer world at the Apple World Wide Developers Conference (WWDC) 2014 with the announcement of a new programming language: Swift. The aim of Swift is to replace Objective-C with a much more modern language syntax without worrying too much about the constraints of C compatibility. Apple itself touted Swift as Objective-C without the C.

For developers already deeply entrenched in Objective-C, it is foreseeable that Objective-C will still be the supported language for iOS and Mac OS X development in the near and immediate future. However, signs are all pointing to Apple’s intention to make Swift the future language of choice for iOS and Mac development.

In this chapter, you will learn about the basics of Swift and how you can set up the development environment to learn it.

WHAT IS SWIFT?

Swift is a new programming language designed by Apple for Cocoa (Mac OS X) and Cocoa Touch (iOS) programming. The syntax of Swift is similar to modern languages such as Java and C#, while at the same time retaining some of the core features of Objective-C, such as named parameters, protocols, and delegates. The language’s clear syntax makes your code simpler to read and maintain.

As an example, consider the following method in Objective-C:

-(int) addOneNumber:(int) num1 withAnotherNum:(int) num2{ return num1 + num2;}

The preceding method adds two numbers and returns their sum. To use the method, you can pass a message to it:

int sum = [self addOneNumber:2 withAnotherNum:7];

Note the verbosity of Objective-C and the use of named parameters in the method name. The following example shows the same method in Swift:

func addTwoNumbers(num1:Int, num2:Int) – > Int { return num1 + num2}

The preceding statements define a function called addTwoNumbers, accept two arguments, and return an integer value. You can call the method like this:

var sum = addTwoNumbers(2,5)

As you can see, Swift’s syntax is simpler and easier to read.

In keeping with Objective-C’s named parameters tradition, you can also use named parameters in methods:

func addTwoNumbers(num1:Int, secondNumber num2:Int) – > Int { return num1 + num2}

You can now call the method using named parameters:

var sum = addTwoNumbers(2, secondNumber:5)

NOTE Chapter 5 discusses functions and named parameters in more detail.

Swift is also designed to be a type-safe language. Variables must be initialized before use. In most cases, you have to perform explicit type conversions when assigning values from one type to another. Also, variables that are not assigned a value cannot be used in a statement and will be flagged as errors.

In Swift, for safety reasons there is no implicit type conversion – you must explicitly convert an Int to a Float (or Double). For example, you cannot implicitly assign an Int variable to a Float variable:

var f: Floatvar i: Int = 5f = i //-error-

Rather, you need to explicitly convert the value into a Float value:

f = Float(i)

NOTE Chapter 2 discusses data types in more detail.

WHY SWIFT IS IMPORTANT

Make no mistake; Apple did not create Swift for the sake of creating a new programming language. With the platform wars heating up, Apple desperately needs a language that will enable it to secure its long-term lead in the mobile platform market. Swift is strategic to Apple in a number of ways:

• It fixes many of the issues developers had with Objective-C – particularly, that Objective-C is hard to learn – replacing it with a language that is both fast to learn and easy to maintain.

• It delivers this easy-to-learn language while retaining the spirit of Objective-C but without its verbose syntax.

• It is a much safer language than Objective-C, which contributes to a much more robust app platform.

• It is able to coexist with Objective-C, which gives developers ample time to port their code to Swift over time.

SETTING UP THE ENVIRONMENT

To test all the Swift examples in this book, you need a Swift compiler. The easiest way to obtain the Swift compiler is to download the Xcode 6 from the Mac App Store (see Figure 1.1).


Figure 1.1


Once Xcode 6 is downloaded and installed on your Mac, launch it (see Figure 1.2).


Figure 1.2


There are two ways to test the code in this book:

Create a Playground project– Playground is a new feature in Xcode 6 that makes learning Swift easy and fun. As you enter each line of code, Playground will evaluate the line and display the results. You can also use it to watch the values of variables as you step through the code. Playground is very useful for examining variable types when you are assigning values to them.

Create an iOS project– You can create an iOS project and test your application using the iPhone Simulator included in the Xcode 6. While the focus of this book is on the Swift programming language and not iOS development, testing your code in an iOS project enables you to test your code in its entirety.

Creating a Playground Project

To create a Playground project, launch Xcode 6 and select File New Playground… Name the Playground project and select the platform you want to test it on (see Figure 1.3).


Figure 1.3


Once the Playground project is created, you will see the editor shown in Figure 1.4. You can start writing your Swift code in this editor. I will show you some of Playground’s neat features as we discuss the various Swift topics covered in this chapter.


Figure 1.4


For example, consider the following code snippet:

var sum = 0

for index in 1…5 {

sum += index

}

The preceding code snippet sums all the numbers from 1 to 5. If you type this code snippet into Playground, you will see that the right side of the Playground window displays a circle (see Figure 1.5).


Figure 1.5


Clicking on the circle will reveal the Timeline, where you can examine the values for sum for each iteration of the For loop (see Figure 1.6).


Figure 1.6


This feature makes it very easy for you to trace through your code, and it is especially useful when you are analyzing your new algorithm.

NOTE The For loop is discussed in more detail in Chapter 7.

Creating an iOS Project

An alternative to creating a Playground project is to create an iOS project. In Xcode 6, select File New Project… and you will see the dialog shown in Figure 1.7.


Figure 1.7


Select Application under the iOS category (on the left) and then select the Single View Application template. Click Next.

NOTE The Single View Application template creates an iPhone project with a single View window. This is the best template to use for learning Swift without getting bogged down with how an iOS application works.

In the next dialog, enter the information as follows (see Figure 1.8):

Product Name– The name of the project.

Organization Name– This can either be your name or your organization’s name.

Organization Identifier– Commonly the reverse domain name of your company. If your organization’s domain name were example.com, then you would enter com.example. The Organization Identifier and the Product Name are concatenated to form a unique string called the Bundle Identifier. Every application listed on the App Store must have a unique Bundle Identifier. For testing purposes, this is not important.

Language– Select Swift.

Devices– Select iPhone.


Figure 1.8


Once the information is entered, click Next and select a location to save the project, and then click Create. Xcode will proceed to create the project. In the created project, select the ViewController.swift file for editing (see Figure 1.9).


Figure 1.9


To test your Swift code, you can insert it in the position indicated in bold in the following example:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

//-insert your Swift code here- println("Hello, Swift!")

// Do any additional setup after loading the view, typically from a // nib.}

override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated. }}

To run the application, select the iPhone 6 Simulator and click the Build and Run button (see Figure 1.10). Alternatively, you can also use the Command+R keyboard shortcut.


Figure 1.10


You should now see the iPhone Simulator appear (see Figure 1.11).


Figure 1.11


As our focus in this book is not on iOS programming, you would be primarily interested in the output generated by your Swift code. Back in Xcode 6, press Command+Shift+C to reveal the Output window. Figure 1.12 shows our single Swift code printing out a line in the Output window.


Figure 1.12


SWIFT SYNTAX

Now that you know how to set up the development environment for learning Swift and have looked at the various types of projects you can create to experiment with it, this section introduces the various syntaxes of Swift, beginning with how to create constants and variables.

Constants

In Swift, you create a constant using the let keyword:

let radius = 3.45

let numOfColumns = 5

let myName = "Wei-Meng Lee"

Notice that there is no need to specify the data type – they are inferred automatically. In the preceding example, radius is a Double, numOfColumns is an Int, while myName is a String. How can the programmer verify the variable type? A good way is to use Xcode’s Playground feature. Go ahead and type the preceding statements into your Playground project. Then, Option-click on each of the constants and look at the pop-up that appears. Figure 1.13 shows that the type of radius is Double.


Figure 1.13


Readers familiar with Objective-C will immediately note the lack of the @ character when defining a string literal. In Objective-C, you need the @ character before a string:

NSString *myName = @"Wei-Meng Lee"

//-

Objective-C-

However, it is not needed in Swift: let myName = "Wei-Meng Lee"

//-

Swift-

Also, in Objective-C you need to use the * to indicate memory pointers whenever you are dealing with objects; in Swift there is no need to use the *, regardless of whether you are using objects or primitive types.

NOTE Strictly speaking, the String type in Swift is a primitive (value) type, whereas the NSString in Objective-C is a reference type (object). Strings are discussed in more detail in Chapter 3.

If you wish to declare the type of constant, you can do so using the colon operator (:) followed by the data type, as shown here:

let diameter:Double = 8

The preceding statement declares diameter to be a Double constant. You want to declare it explicitly because you are assigning an integer value to it. If you don’t do this, the compiler will assume it is an integer constant.

Once a constant is created, you can no longer change its value:

let radius = 3.45radius = 5.67 //-error-

Figure 1-14 shows Playground flagging the statement as an error.


Figure 1.14


Variables

To declare a variable, you use the var keyword:


Figure 1.15


let radius = 3.45 v

ar myAge = 25

var circumference = 2 * 3.14 * radius

Once a variable is created, you can change its value:

let diameter = 20.5

circumference = 2 * 3.14 * diameter/2

Observe that after you type the preceding statements into Playground, the value of circumference is immediately computed and the result shown on the right (see Figure 1-15).

In Swift, values are never implicitly converted to another type. For example, suppose you are trying to concatenate a string and the value of a variable. In the following example, you need to explicitly use the String() initializer to convert the value of myAge to a string value before concatenating it with another string:

var strMyAge = "My age is " + String(myAge)

//-My age is 25-

If you type the preceding statements into Playground, the value of strMyAge is immediately shown on the right (see Figure 1.16).


Figure 1.16


Interestingly, an error will occur if you try to do something such as the following:

var strCircumference =

"Circumference of circle is " + String

(circumference)

This is because the String() initializer cannot convert the Double type (the circumference variable by type inference is Double) into a String type. To solve this, you need to use the string interpolation method, as described in the next section.

NOTE You will learn more about data types in the next chapter.

String Interpolation: Including Values in Strings

One of the dreaded tasks in Objective-C is inserting values of variables in a string. (You have to use the NSString class and its associated stringWithFormat: method to perform string concatenation, which makes your code really long.)

In Swift, this is very easy using the \() syntax, known as string interpolation. It has the following format:

"Your string literal \(variable_name)"

The following example shows how:

let myName = "Wei-Meng Lee"

var strName = "My name is \(myName)"

You can use this method to include a Double value in your string as shown here:

var strResult = "The circumference is \

(circumference)"

Statements

You might have noticed that in the statements you wrote earlier, unlike most other programming languages each statement does not end with a semicolon (;):

let radius = 3.45

let numOfColumns = 5

let myName = "Wei-Meng Lee"

If you want to include semicolons at the end of each statement, it is syntactically correct but not necessary:

let radius = 3.45; let numOfColumns = 5; let myName = "Wei-Meng Lee";

The only time the semicolon is required is when you combine multiple statements into one single line:

let radius = 3.45; let numOfColumns = 5; let myName = "Wei-Meng Lee";

Printing

You can print the current values of variables or constants using the println() or print() function. The print() function prints out the value, whereas the println() function does the same and additionally prints a line break. These two functions are similar to Cocoa’s NSLog function (for readers who are familiar with Objective-C).

In Playground, the println() and print() functions print the values to the Console Output window in the Timeline; in Xcode, these functions print out the values to the Output window. The following statements print out the value of strMyAge:

var strMyAge = "My age is " + String(myAge)println(strMyAge)

Figure 1.17 shows the output of the preceding statements in Xcode’s Output window. (Press Command+Shift+C to reveal the Output window.)


Figure 1.17


Comments

In Swift, as in most programming languages, you insert comments into your code using two forward slashes (//):

// this is a comment

// this is another comment

The // characters mark the line as a comment. The compiler ignores comments at compilation time.

If you have several lines of comments, it is better to use the /* and */ combination to denote a block of statements as comments. For example:

/* this is a comment

this is another comment

*/

The two preceding lines are marked as a comment.

You can also nest comments, as shown in the following example:

// this is a comment

var myAge = 25

var circumference = 2 * 3.14 * radius

var strMyAge = "My age is " + String(myAge)

/* this is a comment

this is another comment

*/

println(strMyAge)

To comment the entire block of code, enclose everything within the /* and */, as shown here:

/*// this is a comment

var myAge = 25

var circumference = 2 * 3.14 * radius

var strMyAge = "My age is " + String(myAge)

/*

this is a comment

this is another comment

*/

println(strMyAge)

*/

NOTE In other languages such as C and Java, you are not allowed to nest comments.

SUMMARY

In this chapter, you learned about Apple’s motives for creating Swift, as well as how to obtain the tools to start learning it. You also had a brief look at its syntax. If you have been an Objective-C developer until now, your first impression of Swift is likely a positive one, as it is a thoroughly contemporary and safe language, without the obscure syntax of Objective-C. In the following chapters, you will learn about various other impressive aspects of Swift.

EXERCISES

1. Declare three constants: to store the number of months in a year, the number of days in a week, and the number of weeks in a year.

2. Declare variables to store a user’s gender, weight, height, and date of birth.

3. Write statement(s) to print out the details of the user using the variables that you have declared in question #2.

4. The following statements resulted in a compiler error. Fix it.

var weight = 102.5 // in poundsvar str = "Your weight is " + weight + " pounds"

WHAT YOU LEARNED IN THIS CHAPTER


Beginning Swift Programming

Подняться наверх