Learn Swift by Building Applications
eBook - ePub

Learn Swift by Building Applications

Explore Swift programming through iOS app development

Emil Atanasov

Compartir libro
  1. 366 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Learn Swift by Building Applications

Explore Swift programming through iOS app development

Emil Atanasov

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Start building your very own mobile apps with this comprehensive introduction to Swift and object-oriented programmingAbout This Book• A complete beginner's guide to Swift programming language• Understand core Swift programming concepts and techniques for creating popular iOS apps• Start your journey toward building mobile app development with this practical guideWho This Book Is ForThis book is for beginners who are new to Swift or may have some preliminary knowledge of Objective-C. If you are interested in learning and mastering Swift in Apple's ecosystem, namely mobile development, then this book is for you.What You Will Learn• Become a pro at iOS development by creating simple-to-complex iOS mobile applications• Master Playgrounds, a unique and intuitive approach to teaching Xcode• Tackle the basics, including variables, if clauses, functions, loops and structures, classes, and inheritance• Model real-world objects in Swift and have an in-depth understanding of the data structures used, along with OOP concepts and protocols• Use CocoaPods, an open source Swift package manager to ease your everyday developer requirements• Develop a wide range of apps, from a simple weather app to an Instagram-like social app• Get ahead in the industry by learning how to use third-party libraries efficiently in your appsIn DetailSwift Language is now more powerful than ever; it has introduced new ways to solve old problems and has gone on to become one of the fastest growing popular languages. It is now a de-facto choice for iOS developers and it powers most of the newly released and popular apps. This practical guide will help you to begin your journey with Swift programming through learning how to build iOS apps.You will learn all about basic variables, if clauses, functions, loops, and other core concepts; then structures, classes, and inheritance will be discussed. Next, you'll dive into developing a weather app that consumes data from the internet and presents information to the user. The final project is more complex, involving creating an Instagram like app that integrates different external libraries. The app also uses CocoaPods as its package dependency manager, to give you a cutting-edge tool to add to your skillset. By the end of the book, you will have learned how to model real-world apps in Swift.Style and approachThis book has a very practical and hands-on approach towards teaching the user the new and advanced features of Swift.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Learn Swift by Building Applications un PDF/ePUB en línea?
Sí, puedes acceder a Learn Swift by Building Applications de Emil Atanasov en formato PDF o ePUB, así como a otros libros populares de Informatique y Systèmes d'exploitation. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2018
ISBN
9781786466013
Edición
1
Categoría
Informatique

How to Use Data Structures, OOP, and Protocols

In this chapter, we will begin with a short introduction of the primary collection types—array, set, and dictionary. Then, we learn how to visually present a collection. Finally, we will finish with a real application that displays information using a list. In the implementation, we will use OOP and protocols to handle the visualization of the data in an elegant fashion.
In this chapter, we will cover the following topics:
  • Primary collection types
  • List of items in a playground
  • Table view in iOS app
  • Protocols

Primary collection types

In Swift, there are three collection types (for simplicity, we will discuss only mutable collections):
  • Array: An ordered (indexed) list of values which are from the same data type
  • Set: An unordered collection of unique values from the same data type
  • Dictionary: An unordered collection map (key -> value), which links a key with a value, and the keys should be unique and from the same data type
Each collection has a fixed data type and there is no way to store values from different data types in the collection. This will become clear later in the chapter.
Array, dictionary, and set are implemented using generics and are called generic collections.

Generics

Generics is a pattern approach to defining custom types or functions. They can work with any type that meets the desired requirements. This is a really powerful feature of Swift. The Swift standard library contains many classes, structures, enumerations, and functions which are defined as generic types.
This is why you can create different collections which contain either string or int, and Swift handles this without a problem. There is one robust generic implementation of the array structure which handles all different cases.
To illustrate the generics, we will define a generic structure which contains a raw data field and description, which is a string:
struct Item<T> {
var raw: T
var description: String

init(raw: T, description:String = "no description") {
self.raw = raw
self.description = description
}
}
var itemInt:Item<Int> = Item(raw: 55, description: "fifty five")
print("This is an int \(itemInt.raw) with description - \(itemInt.description)")

var itemDouble:Item<Double> = Item(raw: 3.14, description: "Pi")
print("This is an int \(itemDouble.raw) with description - \(itemDouble.description)")
This shows that we can create different concrete classes, where the template classes listed in brackets (like < T >) are linked with real data types.
Similar to structures, classes and enums can be defined in the same generic manner. Every generic type can be used only if the template types are linked with an exact data type that fulfills the requirements.
Let's get familiar with the details of some data collections that saw earlier in the book. The first collection type is array.

Array

If you want to store values of the same type in an ordered list, then you have to use an array collection. The collection is part of Swift and it is implemented as a structure. There is an easy way to access each value—using its index (it should be valid). The same values can appear many times at different indices.
The array type is generic, which is why we can create arrays which hold different types of data such as strings, ints, doubles, and custom data types. Here is how you can define an array of string values:
var words = Array<String>(arrayLiteral: "one", "two", "three")
// short syntax using literals
//var words = ["one", "two", "three"]

for word in words {
print(word)
}
Swift is pretty clever and can easily figure out the type of an array, which is declared using an array literal (list which is enclosed with [ ]). (The previous example contains an example in the comments.)
To create an empty array (of ints), you can use one of the following approaches:
//empty array of int-s
var emptyArrayOfInts = [Int]()
//empty array of int-s
var emptyArrayOfInts2 = Array<Int>()
//the variable type is Array<Int> and the value is empty Array
var emptyArray:[Int] = []
Also, you can use the handy constructor to create a list of repeating values from a certain type:
var tenZeros = Array(repeating: 0, count: 10)
print("The number of items is \(tenZeros.count).")
Be careful when using the aforementioned initializers. When you create an array of repeating objects, the passed object will be shared and will be used in the array.
If you have two arrays, the default operator + works like a concatenation of the two arrays in a new one. For example:
var even = [2, 4, 6]
var odd = [1, 3 ,5]
var concatenated = even + odd
print(concatenated)
When working with arrays, you will need some pretty handy functions, which are part of the array interface. Let's check some of them out:
  • .count: A property, which is read-only and returns the number of items in the concrete array instance
  • .isEmpty: A property, which is read-only and returns true if, and only if, the array instance has no items
  • .append(_:): A function which appends an item to the array instance (add the new item to the end of the list); an alternative option is to use the += operator
  • .insert(_:at:): A function which inserts an item at a specific position in the array instance
  • .remove(at:): A function which removes an item at the specific positions, but the position (index) should be correct; the removed item is returned
Subscripts are a pretty neat way to access particular item(s) using the correct position in the array. The positioning starts from 0. Subscripts with ranges can be used to get a slice of the items without any trouble.
The minimal index in an array is 0. The maximal valid index for any non-empty array is array.count - 1:
//the concatenated array contains [2, 4, 6, 1, 3, 5]
var part = concatenated[2...4]
print(part)
//prints [6, 1, 3]
Range types are used to define sets of indices. They could be half-opened ranges or closed ranges—2..<4 includes 2 and 3; in contrast 2...4 contains 2, 3, and 4.
There are many ways to iterate over items in an array. We can use the for...in loop like so:
for value in concatenated {
print("Item: \(value)")
}

for (index, value) in concatenated.enumerated() {
print("Item #\(index + 1): \(value)")
}
The first for loop goes through all values in the array. The second one does the same, but we have assigned indices to all items and we can use those to enumerate each item.
Now, let's get familiar with a set collection, which stores only unique values and there is no order.

Set

Set is a collection which stores values of the same type, but just a single copy of it. There is no orde...

Índice