The book "Swift. Basics of developing applications for iOS and macOS. 4th ed. supplemented and revised "

    imageThis book contains comprehensive information for everyone who wants to learn how to program in the wonderful Swift language in order to create their own iOS-applications (including macOS, tvOS and watchOS) or programs for the Linux operating system. During the reading of the book you will come across not only theoretical information, but also a large number of practical examples and tasks, by completing which you will deepen your knowledge of the material being studied.

    During a long and fruitful conversation with many of you, a lot of ideas were developed that made the new edition really useful. Compared with the previous edition, this book contains the following changes and additions:

    - All material is updated in accordance with Swift version 4.1 and Xcode 9.
    - Added a large number of new educational material, in particular, related to the practical development of applications for iOS.
    - Improved the chapter on the String data type.
    - Considered the wishes and comments of users on the design and content.
    - Fixed typos found. Material intended for novice programmers has been allocated in separate blocks to allow readers with experience in developing in other languages ​​not to be distracted by material that they do not need.

    Book structure


    The book consists of five large parts and one application:

    Part I. Preparing for the development of Swift applications . In the first part, you will begin your journey into the world of Swift, follow the most important and necessary steps that precede the start of developing your own applications. You will learn how to create your own Apple ID account, how to connect to the apple-developers program, where to get the Swift-application development environment, how to work with it.

    Part II Basic features of Swift . After familiarizing yourself with the Xcode development environment, which allows you to start learning a programming language, you will learn the basic features of Swift. You will find out what syntax Swift has, what variables and constants are, what data types exist, and how to use all this when developing programs.

    Part III. Fixed assets Swift . The third part focuses on the consideration and study of the most simple, but very interesting Swift tools. You may never have heard of some of them (for example, tuples), others (for example, arrays) you probably used in other languages.

    Part IV Non-trivial features of Swift . The fourth part describes in detail how to work with the most powerful and functional Swift tools. You will use the material of this part with enviable regularity when creating your own applications in the future. Also a distinctive feature of this part is a lot of practical work on creating the first interactive application.

    Part V. Application Development Fundamentals. At the end of a long and exciting way to learn the language and create some simple applications in Xcode Playground, you will plunge into the world of developing full-fledged programs. In this section, you will learn the basics of creating interfaces and how programs work in Xcode "under the hood." All this in the future will allow you to successfully master new material and create beautiful projects.

    Application. Changes and innovations of Swift 4.0 . If you studied any of the previous versions of Swift, then the information provided in this application will allow you to quickly get acquainted with all the innovations and changes that the new version of the programming language brought.

    Excerpt from a book. 29.3. Type restrictions


    It is sometimes useful to specify certain restrictions imposed on data types of a universal template. As an example, we have already considered the Dictionary data type, where there is a requirement for a key: the data type must comply with the Hashable protocol.

    Universal templates allow you to impose certain requirements and restrictions on the value data type. You can specify a list of types that the value type must match. If the element of this list is a protocol (which is also a data type), then the correspondence of the value type to this protocol is checked; if the type is a class, structure, or enumeration, then it is checked whether the type of the value matches the given type.

    To define the constraints, it is necessary to transfer the list of type names through the colon after the placeholder of the type name. We implement a function that searches for an element in an array and returns its index (Listing 29.7).

    NOTE To provide functionality for comparing two values, Swift has a special Equatable protocol. It obliges the supporting data type to implement the functional of comparing two values ​​using the equality (==) and inequality (! =) Operators. In other words, if the data type supports this protocol, then its values ​​can be compared with each other.

    Listing 29.7

    1  func findIndex(array: [T], valueToFind: T) -> Int? {
    2      for (index, value) in array.enumerated() {
    3          if value == valueToFind {
    4              return index
    5          }
    6      }
    7      return nil
    8  }
    9  var myArray = [3.14159, 0.1, 0.25]
    10  let firstIndex = findIndex(array: myArray, valueToFind: 0.1) // 1	
    11  let secondIndex = findIndex(array: myArray, valueToFind: 31) 
        // nil

    The type parameter is written as . This means "any type that supports the Equatable protocol." As a result, the search in the transferred array is performed without errors, since the Int data type supports the Equatable protocol, therefore, values ​​of this type can be accepted for processing.

    29.4. Generic Type Extensions


    Swift allows you to extend the described generic types. In this case, the placeholder names used in the type description can also be indicated in the extension.
    We extend the previously described universal Stack type by adding a computed property that returns the top element of the stack without deleting it (Listing 29.8).

    Listing 29.8

    1  extension Stack {
    2      var topItem: T? {
    3          return items.isEmpty ? nil : items[items.count — 1]
    4      }
    5  }

    The topItem property uses a T type name placeholder to indicate the type of property. This property is optional, since there may be no value in the stack. In this case, nil is returned.

    29.5. Related Types


    When defining a protocol, it is convenient to use related types that point to some, as yet unknown, data type. The associated type allows you to specify a data type placeholder that will be used when filling out the protocol. In fact, the data type is not specified until the protocol is accepted by any object type. Associated types are specified using the associatedtype keyword, followed by the name of the associated type.

    Define the Container protocol using the associated ItemType type (Listing 29.9).

    Listing 29.9

    1  protocol Container {
    2      associatedtype  ItemType
    3      mutating func append(item: ItemType)
    4      var count: Int { get }
    5      subscript(i: Int) -> ItemType { get }
    6  }

    The Container protocol can be used in various collections, for example, in the Stack collection type described earlier. In this case, the data type used in the properties and methods of the protocol is not known in advance.

    To solve the problem, the associated type ItemType is used, which is determined only when the protocol is accepted by the data type. An example of accepting a protocol for execution by the Stack data type is shown in Listing 29.10.

    Listing 29.10

    1  struct Stack: Container {
    2      typealias ItemType = T
    3      var items = [T]()
    4      var count: Int {
    5          return items.count
    6      }
    7      init(){}
    8      init(_ elements: T...){
    9          self.items = elements
    10      }
    11      subscript(i: Int) -> T {
    12          return items[i]
    13      }
    14      mutating func push(item: T) {
    15          items.append(item)
    16      }
    17      mutating func pop() -> T {
    18          return items.removeLast()
    19      }
    20      mutating func append(item: T) {
    21          items.append(item)
    22      }
    23  }

    Since the Stack type now supports the Container protocol, three new elements have appeared in it: a property, a method, and a subscript. The typealias keyword indicates which data type is associated in a given object type.

    NOTE Note that the associatedtype keyword is used to describe the protocol, and typealias is used to describe the structure.

    Since the name placeholder is used as the type of the item argument of the append property and the return value of the subscript, Swift can independently determine that the placeholder T points to the ItemType type corresponding to the data type in the Container protocol. It is not necessary to specify the associatedtype keyword: if you delete it, the type will continue to work without errors.

    »More details on the book can be found atpublisher’s website
    » Table of Contents
    » Excerpt

    For Habrozhitelami 20% discount on coupon - Swift

    Also popular now: