Programming iOS With Swift 5.3 For Beginners To Pro in 1 Hour (2021 Edition) - A Crash Course On Developing iOS and Mac Apps Using Swift 5.3 and Xcode 12.3
Programming iOS With Swift 5.3 For Beginners To Pro in 1 Hour (2021 Edition) - A Crash Course On Developing iOS and Mac Apps Using Swift 5.3 and Xcode 12.3
Swift 5.3
For Beginners to Pro
In 1 Hour
(2021 Edition)
A Crash Course on Developing iOS and Mac Apps Using Swift 5.3 and
Xcode 12.3
Robert Kissinger
Copyright
Copyright©2021 Robert Kissinger
All rights reserved. No part of this book may be reproduced or used in any
manner without the prior written permission of the copyright owner, except
for the use of brief quotations in a book review.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for
any errors or omissions that may be made. The publisher makes no warranty, express or implied, with
respect to the material contained herein.
Ground of Being
The normal layout of the Swift program is such that there are only one
statement and one line. There are several lines in a Swift text file, but a
statement represents a complete Swift command.
Example print ( “hello“ )
print ( “world” )
These statements can be combined to make a line by putting semi-colon
between them,
print ( “hello“ ) ; print ( “world” )
Multiple lines can also be used for a single statement,
print (
“world” )
A line with a comment contains two slashes after it, this is a variant of the
C++ programming,
print ( “world” )// (Swift will usually ignore this type of comment)
Comments can also be enclosed in /’*………..*/ in a variant of C
programming.
Curly braces are used by many constructs in Swift as delimiters
class Dog {
func bark ( ) {
print ( “woof” )
}
}
These curly braces are normally indented for clarity
Class Dog { func bark ( ) { print ( “woof” ) }}
The Swift language codes must pass through the compiler and change from
text to a language easily understood before running and function. You will
often need to fix several running issues flagged by the compiler, but
sometimes it will just warn you. A warning means your codes can run, but it
is always necessary that you fix any issues flagged by the compiler whether
such a program can run or not.
When the compiler flags any error, you should know that something is wrong
with your coding line. It is advisable to divide the lines of codes into a
simpler part, making you know where the problem is coming.
Object
An object represents a body that can receive a message or command and
execute it. For instance, you can tell your toddler to "sit," "dance," etc. Here,
your toddler represents the object and will execute the message/instruction (to
sit or dance).
Swift uses a dot-notation as the syntax to send a message. The object comes
first, then the dot, followed by the message.
fido . bark ( )
rover . sit ( )
This dot-notation can be broken into more lines
rover
. sit ( )
Object type
Structs, classes, and enums are the main object type in Swift. Enum and
struct exist in Objective-C but not as objects. Enum particularly can be sent a
message, and struct in Swift are significant for a universal programming.
Variables
A variable refers to an object, and it has a value. Variables are normally
declared in Swift; if you want to declare, you use var or let.
Let one = 1
Var two = 2
Since you have declared your variable, you can now use them. Additionally,
we can alter the value of two to be the same as that of one.
Let one = 1
Var two = 2
Two = one
The third line of the above code uses the name one, and the name two
declared in the first two lines. The name one (on the right of the equal sign) is
merely used to refer to the value 1. The name two (on the left of the equal
sign) is used to replace the value. Therefore, when we say two = one, the
value of two was 2 before it became 1.
The equal sign used here is an assignment operator, while the states with the
variable name on the left of the line are the assignment. The equal sign is
rather a command than the algebraic assertion of equality, translated as
"replace what's on my right side with the value of what's on my left side."
The value of a variable declared with let is constant and will not change;
hence, the lines declaration below will not compile.
Let one = 1
Var two = 2
One = two // compile error
Always use let to declare a name that will not change; otherwise, use var for
better flexibility.
Functions
Executable codes like print ( “hello” ) or fido . bark ( ) should be inside the
body of a function. A function is a set of code that is told to run. A function
gets its name through function declaration.
Func go ( ) {
Let one = 1
Var two = 2
Two = one
}
The above describes the sequence of tasks to be done, which is a declaration
of one, declaration of two, changing the value of two for one. This sequence
can, however, be performed when you call the function.
Object members
Special names are given to things declared at the highest level in the object
types (struct, class and enum). Using the Manny example for instance
class Manny {
let name = “many”
func sayName ( ) {
print ( name )
}
}
In the above code,
A name is a variable declared at the top level of the object declaration. Name,
therefore, is the object's property.
sayName is a function declared at the top level of the object declaration.
sayName, therefore, is called a method of the object.
Namespaces
The named program region is referred to as namespaces. Namespaces will
help to know the implication of declaring an object at the object's top level.
Class Manny {
Class Klass { }
}
The above is a nested approach used to declare Klass. By doing so, Klass is
hidden inside Manny.
Modules
Namespaces in the highest level of things are called modules. All top-level
declarations of a module are always visible to your code whenever you
import a module without referring to its namespaces. The Swift module
doesn’t need import because your code will implicitly import it.
Instances
All object types (struct, enum, and class) may be instantiated. An object type
declaration means you describe a type, but you instantiate by making a thing
(an instance).
class Dog {
func bark ( ) {
print ( “woof” )
}
}
The function name is used as the name of the object type to create an instance
by calling the function name. Doing this involves the use of parentheses.
let fido = Dog ( )
In the above example, Dog is instantiated (fido), making fido an instance of a
Dog. You may send instant messages to the Dog instances. These messages
are Dog's properties and methods.
let fido = Dog
fido . bark ( )
However, you should know that you cannot use properties and methods as
messages without an instance.
Dog . bark ( ) // compile error
Although a function of Dog . bark ( ) can be declared but is a static or class
function.
Keyword shelf
An object is usually the recipient of messages and it also represents an
instance. The keyword shelf makes it possible for messages to go to an
instance by itself. Supposing we keep the “bark” of the dog as property, we
will normally refer to the property when implementing the bark.
class Dog {
var name = “ “
var whatADogSays = “woof’’
func bark ( ) {
print ( self . whatADogSays )
}
}
Privacy
Object-based programming usually uses privacy provisions for its object
member. This privacy means other objects will not see these members.
class Dog {
var name = “ “
var whatADogSays = “woof”
func bark ( ) {
print ( self . whatADogSays )
}
func speak ( ) {
print ( self . whatADogSays )
}
}
We can alter the property of "whatADogSays," like using that of a cat. Even
though it's undesirable, You can execute it.
let dog1 = Dog ( )
dog1 . whatADogSays = “meow”
dog1 . bark ( ) // meow
Design
You have to instantiate type consistently, and other instances see these
instances according to the scope of the variables that refer to it. Hence, you
will give enough lifetime to instances and make them evident to each other.
Swift will supply much useful object type for you, and real-world interface
objects will focus on your code when programming with iOS.
CHAPTER ONE
Getting Familiar with the essentials
of Xcode
Xcode is the Integrated Development Environment (IDE) and can build apps
in iOS 14. Building such apps, however, involve some technicalities and
familiarity with some things. This familiarity will enable you to have fore-
knowledge about how the programming works.
Technical requirements
For your codes to run smoothly and without having any hitch while
programming, you should ensure that your device has at least 8 GB RAM and
is 64-bit. The disk space should not be less than 200 GB.
Summary
The nitty-gritty of Xcode is exploited in this chapter. We have seen the
technical requirements, how to download the Xcode and its user interfaces,
and o how to start the app using the iOS simulator. All these will be the
foundation for more of what we need to learn as we advance.
CHAPTER TWO
Simple Values and Types
Swift’s Objective-C includes Int used for integer, Bool used for Boolean
values, String used for textual data, and Double and Float used for floating-
point values. The collection types used in Swift include Set, Array, and
Dictionary.
Swift uses familiar types, such as tuples and optional types that handle when
a value is absent. The optional type will either say "there is no value at all" or
“there is a value, but it is equal to X.”
Technical requirements
Swift needs some familiarization with types, as cannot be seen in Objective
C. Swift has type options for its programming. As such, the options for a
particular program are either "there isn't a value at all" or "there is a value,
and it equals x." You should know the foundation of such parameters and
how they are used.
Exploring Operators
Swift’s operators can be divided into two main categories
Summary
Swift's constants or variables' ability to infer the type from the value's store
makes it a Type Inference Language. You can create a constant or variable
without using the type, but it is always good to use type for easy reading.
CHAPTER THREE
Conditionals and Optional
Conditionals and optional are data types in Swift, which are often utilized to
make certain programming decisions. The optional is one of the enums in
Swift programming with two possible values of Some(T) and None, where T
represents the value of the exact data type.
Technical Requirements
For optional, you should note that a value may and may not be contained in
it. Before accessing such a data type, you should know that you may find or
may not find what you need.
Introducing Conditionals
You make use of conditionals to make decisions in the Swift programming.
The statements used are else, if, and else if. Because these conditional
statements involve making a decision, such decisions are called branching or
control flow. For example,
If password == “Open sesame!” {
Cave. open ( )
Treasure. steal ( )
From the above program, here are what can be deduced
● Boolean logic is used to know whether the variable password is
equivalent to the string Open Sesame in the expression password
== “Open sesame”
● The code within the curling bracket will be executed when this
expression is executed to be true. We call this the conditional
body.
You can also combine several conditions if you want to use the else, if, and
else if statement, an instance is
Let color = “purple”
If color == “green”
{
Print ( “I love the color \
( color ) ! “ )
}
Else if color == “blue” ||
Color == “purple”
{
Print ( “I kinda like the color \ ( color )…” )
}
Print ( “I absolutely HATE the color \ ( color ) !!! “ )
}
The above statement has combined the use or else, if and else if. Hence,
expressions in the conditions like this are evaluated one after the other from
the top to the last statement.
Introducing Optional
The default value of optional in the Swift programming is a null value (nil).
Hence, optionals are used when you want a constant or variable to contain no
value. This optional type means that it may and may not contain a value (i.e.,
a null value).
To declare optionals, you only need to add the ! or ? sign to the data type. An
optional with a value will return as Optional<value>, if no value is contained,
it will return as nil. For example,
var someValue : Int?var someAnotherValue : Int! print
(someValue)
print (someAnotherValue)
When the above program is run, the results will come back as
Nil
Nil
However, our example has initialized an optional type using both! and ?.
Although you are valid if you use any of these ways to create such optional
types, some differences exist.
When you declare an optional type like Int, the variable will either have no
value or have an integer value. The output for such with no value assigned to
the variable, both print statement output nil appear on the screen.
Summary
You have been introduced to how conditions and optionals work in this
chapter. Including how to use the else, if, and else if statements. As far as we
know, optionals may operate without conditionals since it is straightforward.
Conditionals may serve a bit more expressive, though. You have, however,
known how these two operate.
CHAPTER FOUR
Range Operators and Loops
In Swift, range operators express value ranges since a range represents an
interval of values. Range values are often sequential so that they always
follow a regular pattern and easily read. Coding in Swift also requires
executing some basic statements several times, and the loop statements are
always used for this.
Technical Requirements
You should know that the start of a range must be equal to or less than its
end, and you may use such a range operator to access some elements of an
array. You should also know that you can create and combine patterns of
loops for easier programming.
Exploring range operators
There are two range operators used in Swift to express ranges of values
● Half-Open Range: (a..<b) is described as a range of values from a to
b, but this value does not include b. For example, 1…<5 is interpreted
as 1, 2, 3, and 4. In this Range, 5 is not included.
Another instance for this is,
// 1..<3 defines a range containing values 1, 2 for value in 1..
<3 {
print ( value )
}
The output of the above program when you run it will be
1
2
● Closed Range: (a…b) is described as a range of values from a to b and
includes the values of both a and b. For example, 1…5 is interpreted as
1, 2, 3, 4, and 5.
Another programming instance is
// 1…3 defines a range containing values 1, 2, and 3 for value
in 1…3 {
print ( value )
}
The output of the above program when you run it will be
1
2
3
Exploring loops
The major types of loop statements occur in the Swift programming language
include
● For-In loops: The For-In loop has its structure as follows
for <incrementValue> in
<sequence> { //
Statements…}
An example of this is
For I in 1…5
print ( “Outer loop iteration”, i )
for j in 1…2 {
print ( “Inner loop iteration “, j )
print ( “i = \ (i); j = \ (j)” )
}
}
The above code has the following output
Outer loop iteration 1
Inner loop iteration 1
I=1;j=1
Inner loop iteration 2
i=1;j=2
Outer loop iteration 2
Inner loop iteration 1
i=2;j=1
Inner loop iteration 2
i=2;j=2
Outer loop iteration 3
Inner loop iteration 1
i=3;j=1
Inner loop iteration 2
i=3;j=2
Outer loop iteration 4
Inner loop iteration 1
i=4;j=1
Inner loop iteration 2
i=4;j=2
Outer loop iteration 5
Inner loop iteration 1
i=5;j=1
Inner loop iteration 2
i=5;j=2
The above programs show that the outer loop iterates 5 times while the
inner loop iterates 2 times in each of the outer loop.
● While-loop: A while loop is contained as a statement in another while
loop in this type of programming. Several numbers of while loops may
exist in this case. For example,
var i = 1while i = <= 5 {
print ( “Outer loop iteration ”, I )
var j = 1
while j <= 2 {
print ( “Inner loop iteration ‘, j )
print ( “I = \ (i) ; j = \ (j) ‘ )
j += 1
}
I += 1
}
The output of this program is
Outer loop iteration 1
Inner loop iteration 1
I=1;j=1
Inner loop iteration 2
i=1;j=2
Outer loop iteration 2
Inner loop iteration 1
i=2;j=1
Inner loop iteration 2
i=2;j=2
Outer loop iteration 3
Inner loop iteration 1
i=3;j=1
Inner loop iteration 2
i=3;j=2
Outer loop iteration 4
Inner loop iteration 1
i=4;j=1
Inner loop iteration 2
i=4;j=2
Outer loop iteration 5
Inner loop iteration 1
i=5;j=1
Inner loop iteration 2
i=5;j=2
● Repeat-while loop: A repeat-while loop is contained as a statement in
another repeat-while loop. Several repeat-while loops may exist in this
case. For example,
var i = 1repeat {
print ( “Outer loop iteration “, i )
var j = 1
repeat {
print ( “Inner loop iteration “, j )
print ( “ i = \ (i) ; j = \(j) “ )
j += 1
} while (j <= 2)
i += 1
} while (I <= 5)
The output of the above is
Outer loop iteration 1
Inner loop iteration 1
I=1;j=1
Inner loop iteration 2
i=1;j=2
Outer loop iteration 2
Inner loop iteration 1
i=2;j=1
Inner loop iteration 2
i=2;j=2
Outer loop iteration 3
Inner loop iteration 1
i=3;j=1
Inner loop iteration 2
i=3;j=2
Outer loop iteration 4
Inner loop iteration 1
i=4;j=1
Inner loop iteration 2
i=4;j=2
Outer loop iteration 5
Inner loop iteration 1
i=5;j=1
Inner loop iteration 2
i=5;j=2
Summary
In this chapter, we have explored the use of loop and range in programming,
the different types of range operators and loops. And we have seen that loops
can be programmed in such a way that any types of nested loops we use give
us the same result.
CHAPTER FIVE
Collection types
You can store collections of values in different collection types that are
provided in Swift. These collection types include arrays, dictionaries and sets.
While collection values of arrays are ordered, sets have an unordered type of
collection value. Dictionaries also use unordered collections of key-value
associations.
Technical Requirements
You should know that you cannot input a wrong value of any collection type
in your Swift code. It would be best if you were not mistaken so that you can
be poised about your codes. This collection is mutable, and you should know
when to choose to use a mutable item or an immutable one.
Understanding arrays
Unlike a variable, an array can have many values as possible because it
appears in the form of a numbered list. For instance
1
2
let names = [ “Arthur”, “Ford”, “Tr:
print ( names )
In the above, an array has been created, which was assigned to the constant
name. This array is printed out as the value of the name.
Understanding dictionaries
The Swift programming offers a unique key identifier to save values that can
later be referenced using the same key.
To create a dictionary, you can use initializer syntax, e.g.
var someDict = [KeyType : ValueType] ( )
You can create an empty dictionary using the Int type as key and strings
as the associated value e.g.
var someDict = [Int : String] ( )
A good example of a program of dictionary is
let scores = [
“Bob” : 42
“Alice” : 10
“Diasy” : 33
]
Print ( scores )
Mutability exists so that when you use the let constant to initialize a
dictionary, you cannot alter the items again. As such, the collection is
immutable. A mutable collection is usually started with the var declaration,
and we can alter items in such collections.
Understanding sets
You use a set for a one-dimensional list or collection of items. If we want to
create a set to be known as a fruit. We say
let fruit : Set = [ “apple”, “banana”,
print ( fruit )
We have used the literal syntax to create the fruit set in the above code; we
can add other items to this set as follows
Var fruit = Set<String>( )
Fruit . insert ( “pineapple” )
print ( fruit )
There are several empty functions in a set; they include
● First, which returns the first item in the set.
● isEmpty, which returns true when the set has no item.
● First (where:), which returns a satisfying item.
● count, which returns the set's number of items.
● randomElement (), which returns the set's random item.
Summary
We have seen the use of the different types of collections in Swift
programming in this chapter. We are exposed to how we can create these
collection types and how they could be similar or different from each other
while coding.
CHAPTER SIX
Functions and Closures
A function is used in Swift for some collections of statements having a
specific assignment. You may write this function in a complex form, just like
an Objective C function, or maybe as simple as a C function. You use
closures as your code's functional blocks; these closures are comparable with
what is obtained in the C, Objective-C or lambda programming languages.
Technical Requirements
Expressions involving closures follow crisp, optimization, and lightweight
syntax styles and are usually identical to many, self-contained functions
grouped as blocks. Because many variables and constants are captured in
closures, you should know that they function as a special closure type.
Understanding Functions
The function makes us transfer global and local parameters
● Function definition: The function definition has to do with the real
function body.
● Function declaration: Function declaration tells the compiler about
the parameters, name, and type of function.
In general, a function’s argument should follow the syntax below
Func funcname (parameter)
-> return type {
Statement1Statement2
--- Statement N
Return parameters}
In the instance below, we declare the program's name as a data string in the
"program" function. You should note that it will return the name of the
student if the function is called.
Func program ( name: String
) -> String {
}
print ( program ( name :
“Hello” ) )
print ( program ( name :
“World” ) )
Understanding Closures
Closures store several contexts of variables and constants. A special case of
closure is the nested and global functions. Closure generally fall into three
divisions
● Closure expression: Closure expressions are unnamed lightweight
syntax codes that capture values from the surroundings.
● Global functions: These are named closures which do not capture any
value.
● Nested functions: These closures have a name and also captures values
from the enclosing functions.
The syntax code of closures can be represented by
{ ( parameters ) -> return
Type in statements}
For example
let closureexample = {
print ( “Swift Closures ) }
closureexample ( ) The below closure example takes two Int
parameters and returns an integer.
{ ( Int, Int )
-> Int in Statement1
Statement2 ---
Statement n } let multiply =
{
Val1 : Int, val2 : Int ) –
>Int in
Return val1 *val2
} let result = multiply (
10 , 20 ) print ( result )
The output for the above program will be 200
Summary
We now have the idea of how Swift functions and closures work in this
chapter. We will be using functions when we need to group a few statements
that perform particular tasks together. Closures are intentional codes and may
need a lot of practice, especially if you want to manage memory.
CHAPTER SEVEN
Classes, Structures, and
Enumerations
It is easier to use struct by default when using Swift, but when are you
supposed to use class or enums. Structs enable codes to be more flexible for
use. We already know that structs are value types and classes are reference
types. You do not need to create another interface to implement files for
classes and structures.
Technical Requirements
You need to know that you define both classes and structure using a single
file. You should know that other codes can use the external interface to that
structure or class by doing this. You can also define classes' methods and
properties, only that you will need to implement files and create an interface.
Enumerations allow you to work with a safe code because it defines a
common type for corresponding values. Hence, your provision of values for
any case of enumeration may not be necessary.
Understanding Classes
Swift classes are made of flexible constructs of building blocks. These
classes define properties to store values and initialize methods for improved
function. From the syntax below
Class classname {
Definition 1
Definition 2
---
Definition N
}
The class definition will follow as
Class student {
var studname : String
var mark : Int
var mark2 : Int
}
The syntax to create instances will be
Let studrecord = student ( )
For example
Class MarksStruct {
Var mark : Int
Init ( mark : Int ) {
Self : mark = mark
} } class studentMarks {
var mark = 300 } let marks = studentMarks ( ) print ( “Mark is \
(marks.mark)”)
The result for the above program is 300
Understanding Structures
Structs are important for simple data types and value type structs like String
are easy for coding. You can use and define struct in the sample coding
below
struct NewsItem {
var title : String = “ “
var url : String = “ “
}
var item = NewsItem ( )
item. Title = “Comparing Classes
vs. Structs in Swift."
item.
URL =
"HTTP : //learnappmaking.com/classes-structs-comparison-swift-
programming”
print (item)
// Output : NewsItem ( title :
“Comparing Classes vs. Structs in Swift
," URL :
"HTTP : //learnappmaking.com/classes-structs-comparison-swift-
proramming”)
You will notice that we used the same syntax for defining and using a class
from the above. We used
Struct [name] {…. Instead of class [name]…
Understanding Enumerations
You can use enumerations to store different case values using cases
associated with values of any type. Just like we have seen previously, you
introduce or declare enumeration using enum. Such declaration allows you to
put their definition within the pair of curly braces
Enum SomeEnumeration {
// enumeration
Definition goes here
}
For example, we can use enum for different points of a compass as follows
Enum CompassPoint {
Case north
Case south
Case east
Case west
}
The values of north, south, east, and west defined above are called
enumeration cases. These cases can appear together on a single line and
separated by commas
Enum Planet {
Case mercury, Jupiter, Venus, Saturn, Earth, Uranus, Mars,
Neptune
}
Summary
We have seen how type-safety is introduced in codes with fewer coding
errors by using enums. This chapter has also exposed us to how classes and
structures, though used in similar ways, works when defining specific codes.
CHAPTER EIGHT
Protocols, Extensions, and Error
Handling
A protocol is used to define properties, the blueprint of methods, and some
other requirements that suit a function or task. On the other hand, extensions
allow us to modify types that we don't know by adding functionality to
structures, classes, etc.
Technical Requirements
When using a protocol, you may not know its exact implementation method
until it is implemented. You should know that extensions would give new
initializers, add computed properties and functions, add default
implementations to protocols using protocol extensions, and make an existing
type to conform to a protocol.
Understanding Protocols
Let delve into protocols by considering the following example
Protocol Edible
{
Func eat ( )
}
From the above, the name of the protocol is Edible. It is used for anything
that can be eaten, such as food. A protocol is designed in similar syntax, like
how classes work
Protocol name {
Body
}
You should know that a protocol will define a function but will not
implement it. But we can define a protocol and implement it in a class, just as
below
Class Apple: Edible {
Func eat ( )
{
print ( “Omnomnom! Eating the apple…” )
}
}
From the above, you observe that the Apple class has used the Edible
protocol by separating it with a colon and writing it after the class name. The
Apple class implemented the eat ( ) function by providing a function body via
repeated function declaration fun eat ( ).
Understanding Extensions
We use extensions to organize our codes. An example is if we consider that
we don’t have access to the code of another developer who already defined a
class in his code. If his code looks like this
Class Airplane {
Var altitude : Double = 0
Func setAltitude ( feet :
Double ) {
Altitude = feet
}
}
This developer used feet to measure the altitude of the Airplane. Suppose you
want to use meters, you can use Swift extension since you cannot edit the
developer's code, and you will also not want to subclass Airplane. Your
extension will look something like this
Extension Airplane {
Func setAltitude ( meter :
Double ) {
Altitude = meter *
3.28084
}
}
You can now express an ordinary function by using the function of
setAltitude(meter : ) on an instance of Airplane just like below
let boeing = Airplane ( )
boeing . setAltitude ( meter :
12000)
print (boeing . altitude ) //
Output : 39370.08
Exploring Error Handling
Coding in Swift may come with its errors, but these errors can be handled and
given response to appropriately.
● Throwing Error: Let's consider the code below
If fuel < 1000 {
throw
RocketError . InsufficientFuel
}
The above means that the code is used to throw an error type
RocketError.insufficientfuel if the fuel variable is not up to 1000. If we want
to fire a rocket, then,
Func
igniteRockets ( fuel : Int,
astronauts : Int ) throws {
if fuel < 1000 {
throw
RocketError . insufficientduel
}
Else if astronauts < 3 {
Throw
RocketError . insuffiecientAstronauts ( needed : 3)
}
Print ( “3….2…1…Ignition !!!LIFTOFF!!!!” )
}
The above code means that the function igniteRockets(fuel:astronauts: ) can
only ignite if there are at least 3 astronauts on board and the fuel is more than
or equivalent to 1000.
● The Initial Approach-try!: Consider the code below, which produces
an error from the Swift compiler
Let urls =
FileManager. default . URLs (for :
. applicationSupportDirectory, in : .userDomianMask)
try
FileManager . default . create
Directory (at :
URLs [0], withIntermediateDirectories : true,
Attributes : nil )
We can fix the error above by using the try! approach, which forces
unwrapping
try
FileManager . default . create
Directory (at :
URLs [0], withIntermediateDirectories : true,
Attributes : nil )
Meanwhile, this approach is used when you are sure that the error will not
occur.
● The optional try-try?: We can also make use of Try? To ignore any
error such as below
try?
FileManager. Default.create
Directory (at :
URLs [0], withIntermediateDirectories : true,
Attributes : nil )
● Do-try-catch: It is also possible for us to catch errors
Do {
try FileManager . default
. createDirectory
} catch let err {
print ( err ) // or do something different?
}
The above method sees us creating the directory. We can simply go directly
to the second block, where we can handle the problems.
Summary
You now know that extensions cannot replace the functionality or alter a
class's main structure or other declarations; they can only add functionality.
You can now use the protocol to define rules to conform to an adopting class.
CHAPTER NINE
Setting up the user interface
The Swift user interface will help us to use our codes to build an app we
want. In this chapter, we will look at how to create the Let’s Eat app. We are
going to review the already finished product and see how we can build ours.
Technical requirements
You must set up your storyboard for the Let's Eat app you want to create.
You will also need to know the locations of the Tab bar buttons and the
Navigation controllers. You will need to know how to build the app from
scratch by deleting any existing project using the ViewController.swift file
and add the app assets using the Assets.xcassets folder.
Summary
This chapter has exposed us to how we can create a basic app called Let's
Eat. So far, we have set up the logo and background color using the stepwise
methods of setting up the tab bar controller scene and launching the screen.
CHAPTER TEN
Building your user interface
You have been exposed to the creation of Tab bar controller in the previous
chapter; this chapter will deal with how to create some other View controller
that we need so that we will be able to navigate across the different sections
of the app.
For this app we are building, we will need to add the
RestaurantViewController and ExploreViewController. We can download
this at GitHub (although we can create this for quick use, let's use the
downloaded format first).
Summary
With all that is done in this chapter, we are almost done with our app. We
have been able to create a dummy cell Collection View, which will enable us
to create the rest of the app's structure. Then, we can simulate the design of
the app.
CHAPTER ELEVEN
Finishing up your User Interface
We will try to finish our app in this chapter so that we will now be able to get
the basic structure of our app. This structure will allow us to get ready for any
asset we need before there is any additional coding so that the app's design
will just be the perfect one.
Technical requirement
You will need to be accustomed to integrating the Main.storyboard with the
UITableView, UIViewController, and others for the optimal function of the
app being built. Choosing values is also very important in this chapter, and
you must master the act.
You can now run the project by using the cmd + R or by hitting the play
button
Summary
We are done with the basic structure of the app in this chapter. You may want
to create the app again for perfection because we will be dealing with the
other general aspect of the app in the subsequent chapter.
CHAPTER TWELVE
Modifying and Configuring Cells
We are trying to let our app be very similar to the designs and other specifics
of the Let’s Eat app. We will be modifying and configuring the cells in this
chapter. We will work with the table view cells, collection view cells, etc.
Technical requirements
What we will be doing here involves a series of technical repeated actions
which will give us the exact app we are developing. You should know how to
use the several update methods involving the Size inspector and the
Attributes inspector.
Summary
We have been able to mimic the LetsEat app by formatting cells to match our
design. Although you may write some of the layouts with code, the method
we have used here is easier, especially when dealing with the storyboard.
CHAPTER THIRTEEN
Getting started with MVC and
Collection Views
The Model View Controller (MVC) is a software design pattern that proffers
solutions to common errors in the software design. Because the iOS app is
built using the MVC design pattern, we have three divisions known as
Model, View, and Controller. The Controller has a lot of responsibility
because of the MVC architecture, but we can tweak this pattern to be less
pressure on the MVC.
Technical requirements
You should know that you might find it a little bit difficult when using the
MCV architecture since it makes you uncertain about where to put some
things. The nature of the MCV is such that a lot of responsibility is on the
Controller camp.
You should know that the Controller camp's fundamental importance is to
respond to user's interactions and pass them over to the View or Model camp.
In such a way, any task completed by the Model is passed back to the
Controller. The Controller can now interact with the View. As such, some
technicalities are needed because we will alter the pattern so that less
responsibility will be on the Controller.
Summary
We have learned about how Controllers and classes work and the basic
architecture of the MVC. These structures are paramount to the subsequent
knowledge gained in the following chapters of this book.
CHAPTER FOURTEEN
Bringing Data into Views Collection
You have learned about collection views in the previous chapter, and you've
seen and probably now understand how collection views work on two
different screens. In this chapter, you will be implementing the Explore
screen's model objects to make the screen show a record of cuisines and so
on.
Technical Prerequisite
In this chapter, you will need the previous chapter's knowledge to learn more
about the collection view and how to implement it.
Summary
In this chapter, you learned how to add a property list file to your project.
You also executed the ExploreItem pattern, the Explore screen’s model
objects. You learned how to set up a data manager group,
ExploreDataManager, to interpret data from ExploreData.plist, enter the data
into a group of ExploreItem instances, and give it to ExploreViewController.
You got how to create a controller view for the exploreCell view collection
cell. Lastly, structuring data source methods in the class,
ExploreViewController to utilize data from ExploreItem instances.
CHAPTER FIFTEEN
Introduction to Views Table
In this chapter, we will be looking at how to effect table view controllers,
which will enable you to execute a views table that employs .plist files for a
data source for your apps.
Technical Prerequisite
We will start by learning about how table views work by effecting a view
controller that runs a table view in a code playground. Set up a new
playground and title it ViewTableBasics. You can input and run all the
programs or code demonstrated under the upcoming subheadings as you
move on.
func fetch() {
for location in loadData() {
if let city = location["city"] as? String,
let state = location["state"] as? String {
locations.append("\(city), \(state)")
}
}
}
Breaking down:
loadData() - This loads the location data and returns a group of dictionaries.
Each dictionary saves the state and city of a location.
fetch() - This takes the data given by loadData(), strings the state and city for
each member, and affixes the ensuing string to the array.
numberOfItems() - This returns the count or number of components in the
locations array.
locationItem(at:) - This returns the string reserved in the locations array at
specified array index.
Summary
In this chapter, we looked at table views - how to execute one. Next, we
created the LocationsViewController class, a view table controller for
Locations. Lastly, we produced a data manager group,
LocationsDataManager, to read data from Locations.plist.
CHAPTER SIXTEEN
Introduction To MapKit
In this chapter, we will be looking at what annotations are and how to include
them in a map, build personalized annotations, and move from the screen
map to the restaurant detail screen.
Summary
In this chapter, we talked about what MKAnnotations represent and how to
include them to use them on your map. You also learned how to personalize
your annotations. Your app now moves from hitting on an annotation to a
restaurant information or detail page. Lastly, you learned that extensions help
to sort code and include functionality without changing the main struct or
class with which you are working.
CHAPTER SEVENTEEN
Introduction to JSON files
In this chapter, you will learn how to load and analyze data from JSON files
to utilize in your apps. We will also look at UITableViewDelegate methods
and procedures to move data from a controller view to another.
Technical Prerequisite
You will use your modified project from the previous chapter and continue
working on it.
Summary
We started this chapter by discussing the JSON format, and you created a
data manager group, RestaurantDataManager, that can read JSON files.
Then, you structured the MapViewController class to obtain data from the
RestaurantDataManager instance to exhibit a record of restaurants on the
screen Map.
CHAPTER EIGHTEEN
Showing Data in a Stationary View
Table
In this chapter, you will learn how to make a views table containing static
cells exhibit data and how to produce a made-to-order map image. Therefore,
you will be able to apply these qualities in your apps.
Technical Prerequisite
You will work on the modified project from the preceding chapter.
Summary
In this chapter, we looked at how to make views tables with stationary cells
exhibit data and build a custom image of a map, which you can now execute
in your app. You learned that by creating and connecting outlets for the
RestaurantDetailView manager group, adding methods to viewDidLoad()
to occupy the view table when the Restaurant Detail screen is exhibited.
Lastly, you moved a suitable RestaurantItem instance from the
MapViewController and RestaurantListViewController instances to
RestaurantDetailViewController, allowing it to exhibit data from the
RestaurantItem instance on the screen of Restaurant Detail.
CHAPTER NINETEEN
Introduction to Custom UIControls
In this chapter, you will learn how to generate custom UIControl groups or
classes, operate touch or tinge events, and apply review forms for your apps.
Technical Prerequisite
You will work on the project from the chapter before.
Summary
In this chapter, you produced RatingsView, a new custom subclass of
UIControl from the beginning and integrated it to the Review Form and
Restaurant Detail screens. You customized it to react to touches, enabling a
user to place a restaurant rating on the Review Form page or screen. Lastly,
you executed the ReviewFormViewController class, a controller view for
the Review Form page, and customized the Cancel button.
CHAPTER TWENTY
Introduction to Image Libraries and
Cameras
In this chapter, you will learn how to import or bring in photos to your apps
and add filters to them.
Technical Prerequisite
You will work on the modified project from the preceding chapter.
Comprehending Filters
iOS has a variety of innate filters that you can apply to complement photos.
You can access these filters via the Core Image repertoire or library. Core
Image is an analysis and image processing technology that renders high-
efficiency processing for video and still images. Core Image contains over
170 filters, offering you the ability to add a wide variety of cool effects to
your images.
For this project, you will be applying just ten filters. Download these filters,
put them in a .plist file, and title the file FilterData.plist. Next, import the
file into your app using the steps below:
1. In the Project navigator, produce a new group inside the folder,
PhotoFilter and title it Model.
2. Drag the FilterData.plist file to Model. Ensure you tick Copy items if
needed and hit Finish.
Summary
In this chapter, you imported a .plist file, FilterData.plist, holding the filters
you are applying, created the class, FilterItem to keep filter data, and
produced a data manager class, FilterManager to read the .plist file and
inhabit a range of FilterItem instances. Next, you generated a
ImageFiltering procedure with a method to use filters on photos. Then you
produced the PhotoFilterViewController and FilterCell classes to manage
or run the view collection cells and the Photo Filter page or screen. Lastly,
you included code to PhotoFilterViewController to use a chosen filter on an
image.
Technical Prerequisite
You will continue using the project from the preceding chapter.
12. For attribute uuid, make sure you uncheck Optional in the Data Model
inspector.
Now, you have created the entities needed for your app.
Technical Prerequisite
You will continue on the modified project from the preceding chapter.
Summary
In this chapter, you learned how to create a Mac app from a current iOS app.
CHAPTER TWENTY THREE
Introduction to SwiftUI
In this chapter, you will learn how to create a SwiftUI app that interprets
model objects, hands them over in a list, and permits navigation to another
screen accommodating a map view.
Technical Prerequisite
You will produce a new Xcode project for this chapter.
Technical Prerequisite
You will continue with the modified project from Chapter 22, Introduction to
Apple Silicon Macs.
Summary
In this chapter, you executed a widget for your project that displays the
restaurants located in a particular location.
CHAPTER TWENTY FIVE
Getting Familiar with App Clips
In this chapter, you will learn how to generate, customize and test an
application clip.
Technical Prerequisite
You will continue on the modified project from Chapter 24, Introduction to
Widgets.
Summary
In this chapter, you executed an app clip for your app that displays a
particular restaurant's details.
CHAPTER TWENTY SIX
Examining and Presenting your
App to the App Store
In this chapter, you will learn how to set up and present apps to the App Store
and carry out internal and external examinations for your app.
Technical Prerequisite
A paid Apple Developer account and an Apple ID are needed to conclude this
chapter.
Summary
Now, you have concluded the whole process of building an application and
uploading it to the App Store
About Author