Swift iOS 24-Hour Trainer. Mishra Abhishek

Чтение книги онлайн.

Читать онлайн книгу Swift iOS 24-Hour Trainer - Mishra Abhishek страница 10

Swift iOS 24-Hour Trainer - Mishra Abhishek

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

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

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