Читать книгу Swift iOS 24-Hour Trainer - Mishra Abhishek - Страница 11

Section I
Hello iOS!
Lesson 3
Introducing Swift

Оглавление

Prior to the launch of iOS8, Objective-C was the official language used to make native applications. With the launch of iOS 8, Apple provided an alternative language called Swift. Now it is possible to code iOS (and Mac OSX) applications in both Objective-C and Swift. This book targets Swift 2.0, which is supported on iOS 9 and later. This lesson introduces some of the basic concepts of Swift.

Introducing Xcode Playgrounds

Playgrounds are a new feature of Xcode (available from versions 6 and above) that allow you to rapidly prototype Swift code. You cannot create a complete app in a playground, but if you want to quickly try out an algorithm or just want to get a feel for the Swift programming language, then playgrounds are for you.

To create a playground, you can either select the Get started with a playground option in the Xcode welcome screen (Figure 3.1), or select the File New Playground menu item.


Figure 3.1


Xcode will then ask you to provide a name for the playground as well as the platform. In this book, only iOS playgrounds are explored (Figure 3.2).


Figure 3.2


Xcode will then prompt you to provide a location where the playground should be saved on your hard disk. You can, of course, use any location of your choice.

The main playground screen is divided into two parts (Figure 3.3).

Editor area: This forms the left-hand side of the playground screen and is where you type your Swift statements. Every time you press Enter on your keyboard to type a new line, the playground will try to execute the line you have just finished.

Results area: This forms the right-hand side of the playground and is where results are displayed. When the playground executes a line of Swift code, it will try and put the result in the same vertical position as the line of code that was executed.


Figure 3.3


If the Swift code you have typed in the editor area contains print statements, then the output of these statements will be visible in the console. To display the console in a playground, use the View Debug Area Activate Console menu item.

Constants and Variables

The let keyword is used to create a constant. A constant is a quantity whose value cannot change once it is assigned. The following statement creates a constant called maximumScore with a value of 200:


If you are familiar with programming in C or Objective-C, you will immediately notice that Swift statements do not need to end in a semicolon.

A variable quantity is one whose value can change over the life of the application. A variable is defined using the var keyword as follows:


There are a few rules that you must stick to when it comes to naming constants and variables. Constants and variables cannot begin with a number, contain spaces, or contain mathematical symbols. You cannot change a constant into a variable or vice versa.

Data Types

Unlike C or Objective-C, Swift does not require you to specify a data type when you are declaring a constant or variable. The Swift compiler uses type inference to work out the data type from the value you assign. If, however, you wish to be explicit, you can specify the data type of a constant or variable while declaring them as follows:


Once a constant or variable has been created with a certain type, its type cannot be changed. Table 3.1 lists some of the common data types in Swift.


Table 3.1 Common Swift Data Types


Variables in Swift are classed as either value types or reference types depending on how they behave when they are passed as parameters to a method. (A method is a block of code that will be described later).

A value type is a variable whose value is copied when it is passed as a parameter to a method. Any changes made by the method to the variable only apply to its private copy of the original variable and do not affect the value of the original variable in any way.

A reference type, on the other hand, is passed by reference. If the receiving method changes the value of a reference type then the change will be visible outside the scope of the function.

Comments

Comments are used to add some descriptive text to your code that you want the compiler to ignore. Typically, these are used to provide a human readable description about what is happening in the code for reference purposes. Comments in Swift are similar to C-style comments. A single line comment begins with two forward slashes (//). For example:


When the compiler encounters a line that starts with two forward slashes, it ignores everything on that line.

If you would like to create a comment that spans over multiple lines, you could use multiple single line comments. Alternatively you can use a multi-line comment. A multi-line comment begins with a forward slash asterisk (/*) and ends with an asterisk forward slash (*/) for example:


Strings

A string is a sequence of characters represented by the String type, and each character in a string is of the Character type. For example:


You can initialize an empty string as follows:


If you have programmed in Objective-C, you will be familiar with the concept of mutable and immutable strings. A mutable string is one whose contents can be changed, and Objective-C uses two different classes (NSString and NSMutableString) to indicate whether a string can be mutated. You will be pleased to know that there is only one String type in Swift; mutability is established by creating a string variable. If you wish to create an immutable string, create a string constant as follows:


Strings can be concatenated (added together) to produce longer strings using the + operator as follows:


The variable concatenatedString will now contain "HappyBirthday" (without a space, as there is no space in any of the original strings.

You can append a string to an existing string variable using the += operator as follows:


The variable myString will now contain "two times two is four". The space between is and four is part of the original value of myString.

Swift uses string interpolation to create a new string from a mix of constants, variables, and expressions. If you are an Objective-C programmer, then string interpolation in Swift is similar to Objective-C's [NSString stringWithFormat] class method. This is best explained with an example:


The result of this snippet will be a string that contains "Jason is 84 cm tall." In this example the variables patientName and patientHeight are inserted as \(patientName) and \(patientHeight) placeholders. When the message variable is evaluated, these placeholders are replaced by actual values and any associated type conversions are performed automatically.

Placeholders aren't restricted to names of constants and variables; you can put a complete expression in a placeholder. For example, the statement


will create a string constant called result with the value "4 is equal to four".

Tuples

A tuple is a compound value that groups multiple values. The individual values within a tuple can be of different data types. The following line of code declares a tuple called applicantDetails with two values – the first is an Int, the second a String.


There are a few different ways to access individual values in a tuple. One way is to use index numbers starting at zero:


If you have named the elements in the tuple when it is defined, you can use these names to access individual values, as you can see in the following code snippet:


You can also split a tuple into separate variables, which you can then access as follows:


The output of any of these three methods would be the same:


Optionals

An optional is a new concept in Swift. An optional variable can either contain a value or have no value. The closest thing in Objective-C would be the use of nil to indicate the absence of an object, but in Objective-C, nil cannot be used with primitive data types, structures, or enumerations. Unlike Objective-C, Swift's optionals can be used to indicate the absence of a value for any data type.

While declaring a variable, you indicate that it is an optional by appending a (?) to the data type. Thus, an optional Double is a Double? For example:


If you define an optional without providing a value, it is automatically set to nil. Alternately, you can set an optional variable to contain no value by assigning nil to it as follows:


nil is interpreted as a valueless state to an optional. If an optional contains a value, you can access this value by unwrapping the optional. To unwrap an optional, simply add an exclamation mark to the end of the variable name.

If you attempt to unwrap an optional that has no value, your app will be terminated with a runtime error. You can test whether an optional has a value by comparing it with nil in a simple if statement, as in the following:


Another way to execute a bunch of statements if an optional contains a value is to use an optional binding. An optional binding allows you check if an optional has a value and, at the same time, extract this value into a constant or variable. Optional bindings can only be used in if and while statements, both of which are covered later in this lesson. Consider the following example:


In this example, the optional score will automatically be unwrapped into the constant unwrappedScore if it contains a value. unwrappedScore can now be used just like a normal constant and does not need any further unwrapping.

If an optional is guaranteed to always contain a value, then you can skip having to unwrap it every time by implicitly unwrapping it when you declare the optional. An implicitly unwrapped optional is declared with an exclamation mark after the data type, instead of a question mark. Attempting to assign nil to an implicitly unwrapped option will result in a compile time error.

Some scenarios where you may want to use an implicitly unwrapped optional are:

• As a return value from a function, this ensures the function will not return nil.

• As an argument to a function, this ensures the function cannot be called with a nil argument.

• When creating IBOutlets to elements in xib files. Interface builder and xib files will be covered in Lesson 9.

In the following example, score is an implicitly unwrapped optional:


Control Flow Statements

A control flow statement allows you to modify the order of statements executed, execute certain statements multiple times, or execute certain statements conditionally.

if-else

The if statement is one such control statement. In its basic form an if statement executes a block of statements only if a specific condition is met.


The test condition is usually a Boolean variable, or an expression that evaluates to a Boolean variable. If the test condition evaluates to true, the following statement (or block of statements) is executed. The following is a simple example:


In this hypothetical game example, a player is required to collect a certain number of red and blue marbles. A player wins the game if he collects more red marbles than blue ones. The test condition in this case is the expression


which evaluates to true in this particular case. Note the complete if statement contains both the test condition and the block of statements that go with the test condition.


Конец ознакомительного фрагмента. Купить книгу
Swift iOS 24-Hour Trainer

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