Learn Swift by Building Applications
eBook - ePub

Learn Swift by Building Applications

Explore Swift programming through iOS app development

Emil Atanasov

Condividi libro
  1. 366 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Learn Swift by Building Applications

Explore Swift programming through iOS app development

Emil Atanasov

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul 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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Learn Swift by Building Applications è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Learn Swift by Building Applications di Emil Atanasov in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Informatique e Systèmes d'exploitation. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2018
ISBN
9781786466013
Edizione
1
Argomento
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...

Indice dei contenuti