Mishra Abhishek

Swift iOS 24-Hour Trainer


Скачать книгу

rel="nofollow" href="#i000004220000.png"/>

      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