Learn Swift by Building Applications
eBook - ePub

Learn Swift by Building Applications

Explore Swift programming through iOS app development

Emil Atanasov

Share book
  1. 366 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Learn Swift by Building Applications

Explore Swift programming through iOS app development

Emil Atanasov

Book details
Book preview
Table of contents
Citations

About This Book

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.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Learn Swift by Building Applications an online PDF/ePUB?
Yes, you can access Learn Swift by Building Applications by Emil Atanasov in PDF and/or ePUB format, as well as other popular books in Informatica & Sistemi operativi. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781786466013
Edition
1

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

Table of contents