Learn Swift by Building Applications
eBook - ePub

Learn Swift by Building Applications

Explore Swift programming through iOS app development

Emil Atanasov

Buch teilen
  1. 366 Seiten
  2. English
  3. ePUB (handyfreundlich)
  4. Über iOS und Android verfügbar
eBook - ePub

Learn Swift by Building Applications

Explore Swift programming through iOS app development

Emil Atanasov

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

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.

Häufig gestellte Fragen

Wie kann ich mein Abo kündigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kündigen“ – ganz einfach. Nachdem du gekündigt hast, bleibt deine Mitgliedschaft für den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich Bücher herunterladen?
Derzeit stehen all unsere auf Mobilgeräte reagierenden ePub-Bücher zum Download über die App zur Verfügung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die übrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den Aboplänen?
Mit beiden Aboplänen erhältst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst für Lehrbücher, bei dem du für weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhältst. Mit über 1 Million Büchern zu über 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
Unterstützt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nächsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist Learn Swift by Building Applications als Online-PDF/ePub verfügbar?
Ja, du hast Zugang zu Learn Swift by Building Applications von Emil Atanasov im PDF- und/oder ePub-Format sowie zu anderen beliebten Büchern aus Informatica & Sistemi operativi. Aus unserem Katalog stehen dir über 1 Million Bücher zur Verfügung.

Information

Jahr
2018
ISBN
9781786466013

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

Inhaltsverzeichnis