What's wrong with Swift programming

Swift Tutorial Part 1: I want to learn Swift and develop apps

"Dad, I want to learn Swift and develop apps," said my fourteen-year-old son.

I must have made a puzzled face, because he shoved right after: "You can help me, right?"

Of course I can help you, I thought, but ...



It wasn't that I thought learning Swift was too difficult. Nor did I think his idea was a short-term whim or fad. Rather, I feared that my son had set himself too high a goal and might lose interest on the way to achieve it.

After all, he wanted to develop apps, probably a game that he could make money from. And all of this within two to three weeks.

Programming an app requires not only mastery of the programming language itself. Rather, one must understand the numerous frameworks that are required to develop an app. Not to mention the object-oriented paradigm that Swift fulfills. But should I tell him all this and dismantle his motivation right away?

Inwardly I sighed and replied, “Cool, I'll help you. All you have to do is swallow a toad: The language is so new that almost everything you can find on the internet is in English. "

"I found a tutorial in German on Youtube," he replied and smiled smugly.

Great, so you can do it without a toad. Do not read, but see and hear. Beautiful new world! I'm kind of old school, I thought.

Something like that, my son brought his request to me a little more than a year ago. What came after that was this: He worked through the video tutorial and I supported him wherever he didn't understand things. I quickly realized that the tutorial only explained the language. It was like learning words and simple grammar, but not learning how to form meaningful sentences.

To fill in the gaps, I gave my son assignments that forced him to apply what he had learned. It was amazing how much knowledge is necessary besides learning the bare language in order to be able to use it adequately. I often had to go back a long way so that I could make him understand a small decision. I had a lot of fun with it - and my son too, I think.

Eventually, he developed his first small iOS app, which he proudly showed off to his family, friends and teacher.

My story would basically end here; after all, my son had achieved his goal. Only I have two sons and the second is in the same direction. So this time I decided to write a tutorial myself that meets all my ideas about what a tutorial should contain and how it should convey the knowledge.

What is the tutorial about?

I am specifically aimed at students interested in learning Swift. That doesn't mean the rest of the population is left out. I am convinced that everyone can benefit from a well-structured tutorial - hopefully I will succeed. In order to achieve that, I thought of the following:

  • At the beginning I explain which program we will develop together in the course of this tutorial. I am NOT going to describe the Swift language using isolated examples. Instead, the program will gradually grow and thus there will be enough opportunities to get to know the language organically and vividly. The development of the program is the common thread that runs through this tutorial.
  • Every time I introduce a new property of language, I briefly leave the red thread, explain the language property and finally come back. The newly acquired knowledge can thus be applied immediately.
  • In the course of the tutorials I will show different ways in which problems can be solved. Also dead ends or wrong paths. In this way, the reader will be able to better understand why a solution can be good or bad.

Let's go: a calculator app with Swift

Okay, let's get started and program a calculator with Swift.

In order to be able to start, the program Xcode must first be called. Xcode is the main tool used to implement programs for Mac, iPhones, iPads or appleTV. It can be downloaded for free directly from the App Store - or from Apple's developer page. In both cases, an Apple ID is required, but it is free.

After Xcode is installed on the Mac, start the program. Like all other programs, it is located under “Programs”.




You can create a new project via the menu item File / New / Project….

As soon as you have done that, a dialog box will appear as shown in the picture. Here you can choose the type of project and the operating system for which you want to program. In our case, we want to develop a command line tool for the macOS platform. This means a program that is supposed to run on a Mac and that does not have a graphical user interface.

Select the platform and type of project as shown in the picture. Then click on Next.



Again a dialog box appears in which you have to provide some additional information. First you give in product name the name of the project. Type in "calculator". team you can ignore it. Under Organization name you can enter your own name unless you own or work for a company. I entered my own name here.

The Organization identifier is a rather technical abbreviation to clearly identify you or your company. Tap de followed by a Point, followed by yoursinitials (or the company name). The so-called Bundle identifier generated, which is composed of your organization identifier and the product name. Finally, you choose as the programming language Swift out. Now click on Next.

 

Now you select a directory in which the project should be created and finish your choice by clicking on Create click.

The project is created and a window appears that looks something like the one shown above. Now click on the file main.swift. Now things can really start.



The project is created, now we open the file main.swift.

Type in the following line:

// 1st attempt print ("1 + 1 = 2")

Now you have to compile the program and then run it. You can do that with the keyboard shortcut + R to reach. You can also click the button with the triangle.



To see what this little program is doing, the console area needs to be visible. The console area is under the program editor where you just typed your first line. If the console area is not visible, you will find a button in the upper right corner of the Xcode window that can be used to make the console area visible. It's the second button from the right - see picture:

You should see the following output in the console area:

1 + 1 = 2

Hey great! Our pocket calculator can do 1 + 1 calculations - right? Can he really do that? Joking aside, of course he can't. The program line

print (1 + 1 = 2)
only caused a text to be output. A text that happens to look like an invoice. We could also have written:

 

print ("One plus one equals 2")

In this case, exactly the text that is written between the quotes appears in the console area. The function print is therefore able to output any text. All well and good, and what does that have to do with a calculator? Well the function print or Swift can do even more.

Now type in the following line:

// 2nd attempt print ("1 + 1 = \ (1 + 1)")

Run the program and you will see the same output in the console window as before, namely 1 + 1 = 2. But what is different this time? The answer is that\(1 + 1) has actually been calculated.

The function print so has a string “1 + 1 = ” and then the result of the sum 1 + 1. This is due to the special spelling \ (X) happen. Here's what happens: X is first evaluated by the Swift compiler (- imagine a compiler as a program that Swift reads and converts into something that the computer can execute, i.e. machine code). Then the result of this evaluation becomes the function print to hand over. And finally the function outputs the evaluated value.

I know this isn't a real calculator either. But at least we found a way to let Swift compute math expressions. We can also write the following:

// 3rd attempt print ("1 + 3 * 7 - 4/2 = \ (1 + 3 * 7 - 4/2)")

In the console area we will now have the output 1 + 3 * 7 - 4 / 2 = 20 find what is a correct result. The operators used here are addition +, subtraction -, multiplication * and division /. As mentioned above, the expression leads \ (X) to that X of the function print is evaluated. In addition to math expressions X also be a variable or constant. To explain this better, type in the following lines:

// 4th attempt let task = "1 + 1" let result = 1 + 1 print ("\ (task) = \ (result)")


Here, too, we get a correct result when we run the program. The result is again 1 + 1 = 2. But this time we have defined placeholders for the values ​​to be output. This is done here through the instructions and. let is a keyword in the Swift programming language and is responsible for introducing a new constant. That is, the constant task stands for “1 + 1”while the constant Result for the result of evaluating the math expression 1 + 1 stands. Or to put it another way: the constant task can store strings and in this example it stores the string “1 + 1”. The constant Result however, stores numbers; in this case the number 2.

You can find a detailed introduction to constants and variables when you open the following topic block “Constants and Variables”. Alternatively, you can of course just read on.


Both constants and variables represent names associated with a value of a certain type. So can the name Age with the value 42 of type number be connected, as in the sentence: My age is 42. Or maybe a little more mathematical: Age = 42. Another example could be the name hobby be the one with the value To go biking connected, which in turn is of the type String (English String) is. The only difference between constants and variables is the ability to change the value they are associated with. A constant can therefore never change its value once it has been assigned; the value is just constant. A variable, on the other hand, changes its value over time. So it makes sense for the name Age is a variable because everything that exists is known to grow older. A name, we say Species however, it will never change. For example, I belong to the Specieshuman to, and thus applies to me Species= Human.

What both variables and constants have in common, however, is that they must first be declared and initialized before they can be used. Declared simply means that they are made known to the system. To do this, two things must be specified:

  1. The Names of constants or variables.
  2. The Type of the value to which the constant or variable is connected.

By initialization we mean the fact that a value is assigned to a variable or constant. This value assignment does not necessarily have to take place at the same time as the declaration. It is only important that a value is assigned to a variable or constant before it is read out.

Here is an example of the declaration with simultaneous initialization of a constant Surname and a variable Age. But I have to explain one thing briefly: Swift agreed that names for variables or constants should be written in lower case, regardless of whether they are nouns, verbs or adjectives. There are other conventions, which are described later. But now again, for example.

let name = "Peter" var age = 42

For constants, a declaration begins with the keyword let and for variables with the keyword var, followed by the name. In the example above, the constants Surname and the variables age each assigned a value; this is the initialization. This is done with the equal signs = and the corresponding value to the right of it. Unlike in mathematics, the equal sign does not express equality. It assigns the value to the right of the equal sign to the name to the left of the equal sign. For equality in Swift are the signs == and === responsible. But I will go into this later.

The attentive reader may have noticed that in the above example only names and values ​​are used in the declarations, not types. And this despite the fact that I wrote earlier that the type of a variable or constant must always be specified. Well, that's because Swift is able to infer the type of a variable or constant from its assigned value. In the example above, "Peter" is a string, which means that it is the constant Surname automatically of the type String (String) is. The variable age is of the type Intwhich represents a number. This deriving is called Type inference.

Although Swift masters type inference and the explicit type specification is not necessary as long as a value is assigned in the declaration, a declaration can look like this.

let name: String = "Peter" var age: Int = 42

Here we have the same example, but with the type specification (type annotation) and value assignment. It is up to the reader to decide which of the two variants suits him better. I personally prefer the explicit variant. In my opinion, it is no less legible, forcing me to think about the type while writing.

But what does a declaration look like if the value that is to be assigned has not yet been determined at the time of declaration? Well, you simply leave out the value assignment, but you have to specify the type. This is then a declaration, but not an initialization.

let name: String var age: Int

After the constants are defined, they are used in the function print used. The expression \(task) causes the content of the constant task is issued. The expression \(Result) causes the number 2 is issued.

Now you could get the idea, the constant task with the expression \(output) evaluate and the result of the constants Result as in the following example:

// 5th attempt let task = "1 + 1" let result = "\ (task)" print ("\ (task) = \ (result)")

If you now run the program, you get the following output in the console area: 1 + 1 = 1 + 1.

What happened now? A little tip: Is described in the above-mentioned topic block “Constants and Variables”.

Well the constant task can only store strings, which we have simply specified by assigning “1 + 1”. The line

let result = "\ (task)"


leads to Result only stores strings. That's because the evaluation of the statement \(task) is a string.

Ok, let's be clear: we are able to let Swift evaluate math expressions. At least the four basic operators like addition, subtraction, multiplication and division. We will see in the next blogs that there is much more possible.