Learning Swift — Day 166 to 169

AP Computer Science Principles with Swift

Unit 2: Functions and Abstractions


Procedural Abstraction

The key feature of abstraction is to hide, or encapsulate, the details of how something works. Each level of abstraction is dependent on and encapsulates the ones underneath it, but each of the tasks included in them can be developed and implemented independently from the others as it will rely only on the single level directly below itself.


The main tool for procedural abstraction is a function, which combines detailed steps into a single block of code that can be reused. Some functions have inputs (parameters, internal names) and change their behaviour based on arguments (external names) passed in from their caller. Some have outputs (i.e., they return a value), while some others don’t.

2.1: How the Internet Works

The Internet was designed to be decentralised, so that no single person, organisation, government or the like could control the flow of information.

The Internet Protocol (IP) is a system that enables information to travel between any two computers connected to the Internet. It gives a unique IP address to each device.

Each device on the Internet has a unique IP address that’s used to route data to it. IP addresses are defined as a series of numbers and are allocated by a handful of registries governed by the Internet Assigned Numbers Authority.

Data transmitted over the Internet via IP is broken into chunks called packets. Each packet is marked with extra information, such as the IP addresses of the sender and the receiver, to enable IP to route the packet correctly.

The time elapsed between the transmission and the receipt of a packet is known as latency.

The Transmission Control Protocol (TCP) is built on top of IP to ensure reliable connections between two Internet-connected devices. It handles scenarios such as packets that arrive out of order or packets that are lost in transit and must be resent.

There is a routine for how this exchange of informations works: due communicating computers must introduce themselves (as two people about to enter a conversation), set up some precise rules for how their communication is going to unfold, exchange the agreed upon packets of data before deciding together of common accord to terminate their conversation.

Interestingly enough, IPs deliver their packets independently and it is therefore the responsibility of the TCP to reassemble them and ensure that there is no lost child on the road.

The TCP/IP team is considered the backbone of the Internet.

On top of them we find the Hypertext Transmission Protocol, also known as HTTP. The websites (or all other transmitted data along with the links that connect them together) are encoded through HTML and then transmitted through HTTP.

Internet Security

TCP/IP is very insecure: any server transmitting/receiving data could inspect absolutely everything from it! There are two technologies that come in to help: Transport Layer Security (TLS) and Secure Sockets Layer (SSL).

TLS is a protocol that operates alongside a transport protocol (for example TCP) to provide secure connections. TLS encrypts all the data being transmitted, making it less vulnerable to attackers trying to glance into the contents of the packets passing by.

SSL does basically the same things but it is older than TLS and presents more vulnerabilities, given which it is slowly being sent into retirement.

Now there would be an Assignment to be realised on Keynote. Just, I admit, I have never used Keynote before (apart for showing a presentation I had already received) and it is one of the softwares I really want to learn how to use.

This is a very interesting assignment but from what it looks like I would need between 3 and 4 hours to put it through.

Again, I’m not a student with all the time of this world so I will just have to skip it for the time being.

Data Sets


Here we learn about the concept of metadata, that is all the informations about the file. This could be the date it was shot on, the location, the size, the format, the camera settings and so much more.

We get warned that there are potential privacy concerns associated with sharing photos that contain location metadata. One thing I didn’t know is that we can open a picture in Preview on a Mac, open the Inspector and, in the GPS tab, click Remove Location Info.

The Apple’s Photos app has algorithms integrated that can recognise objects in our images via machine learning but our privacy is protected because all of this computational work is done on our device. I discovered this when I had to change my iPhone after an incident and… all my Wi-Fi passwords were gone, all my metadata gone! But maybe it is better, right?!

2.2 Explore Task Practice 2

This task is aimed at people who are in a class and will teach code review practices, which I find most interesting. I will download the resources and see what they are about.

After reading those documents, pure bureaucracy … I am so happy I have not done this in college… so, so happy!

2.3 Create Tase Practice 2

This looks very promising, as it will teach us to create an interactive Keynote prototype of our app!

We should watch this video from WWDC 2017 called “60 Second Prototyping” for inspiration. Then we should watch this video from WWDC 2016 on Iterative UI design.

Now let me correct what I said before… they didn’t teach us how to do that, they just told us DO IT! Again … They gave us a model and then go copy, you idiot!. Sincerely, I have no time for this now. Let’s move to the next chapter, hopefully there will be something useful.

2.4 Functions

Let’s open the “Functions.playground” file and cross out fingers for it to be something normal.

My hopes were ill-fated, sadly, as this was the same playground I had completed more than a year ago inside the Intro to App Development with Swift book. No luck here…

I will continue only because I am curious about the theory behind things but to me this really seems the same book, just a tiny bit updated … and even that not so much.

2.5 BoogieBot

In this chapter we should learn how to build personalised dance routines that we can save as animated images (GIFs?).

As previously, we should open the “BoogieBot.playground” file and work our way through it.

I opened it, browsed the first three pages and closed it: it is exactly the same as in the other book.

Really outrageous … this material cannot be proposed to people who really want to learn how to code!

2.6 Constants and Variables

Finally some theory here before the exercise.

CS CONCEPT: Modeling and Simulation

This chapter is quite interesting but, again, this is really aimed at someone who has never heard talking about all this.


Models can be built across a wide set of domains and the chosen domain determines how the model and the algorithms of a simulation are built.


Every simulation and its underlying models and algorithm contain forced simplifications of the represented system.


Parameters are the settings that control the way things work in a simulation.

Fidelity and Time

The higher the complexity of a model and the greater amount of detail one wants to have in the output, the more work it takes to simulate on a computer. When one designs a simulation we need to place it on fidelity-time efficiency line.

The “Ant.playground” was indeed nice, something different at least!

Eventually I managed to have some fun with the “Constants and variables.playground” file. I chose to get independent and create a program for playing PIKADO, the dart-throwing game.

I refined it today (14. August) and it seems perfect now!

import GameplayKit

var score = 501
var roundScore = 0
var round = 1

var playerOneHasPlayed = false
var playerTwoHasPlayed = false

var playerOneScore = 501
var playerTwoScore = 501

func launchDart(player: Int) {
    // Create 3 random throwers
    let gaussianD100 = GKGaussianDistribution(lowestValue: 1, highestValue: 100)
    let gaussianD50 = GKGaussianDistribution(lowestValue: 1, highestValue: 50)
    let gaussianD20 = GKGaussianDistribution(lowestValue: 1, highestValue: 20)
    // Generate point assignment rules
    if gaussianD100.nextInt() == 100 {
        print("Target hit: Bull's Eye)!")
        roundScore += 50
    } else if gaussianD50.nextInt() == 50 {
        roundScore += 25
        print("Target hit: almost in the Bull's Eye)!")
    } else {
        let hitScore = Int.random(in: 1...20)
        if (18...19).contains(gaussianD20.nextInt()) {
            print("Target hit: double \(roundScore)!")
            roundScore += hitScore * 2
        } else if gaussianD20.nextInt() == 20 {
            print("Target hit: triple \(roundScore)!")
            roundScore += hitScore * 3
        } else {
            roundScore += hitScore
            print("Target hit: \(roundScore)")
    // Manage who is playing with two integers
    if player == 1 {
        if playerOneScore - roundScore < 0 {
            print("Invalid throw! Try again next round!")
            playerOneScore -= 0 // necessary??
        } else {
            playerOneScore -= roundScore
        print("Score after round \(round) for player \(player): \(playerOneScore)")
        playerOneHasPlayed = true
    } else {
        if playerTwoScore - roundScore < 0 {
            print("Invalid throw! Try again next round!")
        } else {
            playerTwoScore -= roundScore
        print("Score after round \(round) for player \(player): \(playerTwoScore)")
        playerTwoHasPlayed = true
    if playerOneHasPlayed && playerTwoHasPlayed {
        round += 1
        playerOneHasPlayed = false
        playerTwoHasPlayed = false
    roundScore = 0

func playGame() {
    repeat {
        launchDart(player: 1)
        if playerOneScore == 0 {
            print("Player One Won!")
        launchDart(player: 2)
        if playerTwoScore == 0 {
            print("Player Two Won!")
    } while playerOneScore > 0 && playerTwoScore > 0


2.7 Types

In this unit we will build a program to calculate the circumference of a circle and we will learn how types are used to distinguish between different kinds of values and that every value used in a program, at least in Swift, which is a strongly-typed language, has a type.

Swift is amazing as it makes sure that the types used are used correctly and it will even try to infer the type of values for us.

Just like types of things in everyday life, each type in Swift has its own set of properties and behaviours. Very important: once you set a type on something, it cannot be changed anymore, same as you can’t make a banana into a T-shirt (well…?!)

When we write a new value in code, it is known as a literal and Swift makes an educated assumption about what type that new creation of yours might be! This kind of intuition that Swift makes use of is called type inference.

All Swift’s types come from the Swift Standard Library, something that all programming languages have and that represents the basic set of capabilities required to accomplish fundamental programming tasks.

Types are always written out in Upper Camel Case, in contrast with variable and constant names which are in Lower Camel Case.

In short, types describe what a value is, what it can do and when it can be used!

If you were curious about the exercise mentioned at the beginning of this section, here it is:

let diameter = 2.0
let circumference = diameter * Double.pi

Too exciting to behold, right?!

A bit of theory now: the Foundation framework in Swift defines many types that are used to represent more specific things than just string or numbers from the Swift Standard Library. For example, there are types for dates, distances, and files on a computer, among many others.

2.8 Parameters and Results

In this chapter we will build a function that returns a different sentence based on the values we pass into it. We will learn how to make more powerful functions by passing values into them, indeed, how to make them return values and how to name functions and arguments to make our program readable.

When we call a function we type the function’s name to make the program run the steps contained in the function’s implementation. To call a function with means to use a function’s name with particular arguments: for example, to describe the code greet(name: "John", from: "Washington") in English words, one could say “Call the greet function with John and Washington”. To call a function on or call a method on means to call a method that’s associated with a particular instance; for example, to describe the code trackTimer.reset() in plain English, one could say “Call the “reset” method on the “track timer”.

A caller is the code that uses a function.

A function returns something when it gives an output value back to its caller. The return keyword marks the value that will be passed back to the place where the function was called. Once a line with the return keyword is run, the program jumps back to the line where the function was called and continues executing from there.

Open the “ParametersAndResults.playground” and complete it.

Here is some of the most interesting things I found:

  • when someone uses the function, they can tell the function what the value of the parameter should be. This is called passing in a value. The value we pass in to the function is called the argument.
  • if we wanted our function to take more than one value we should just list the parameters inside the parentheses with a comma between them.
  • Passing a value back when a function is finished is called returning a value. To declare a function that returns a value, we have to add a text arrow -> and the type of the value to be returned.
  • When we call a function that doesn’t have any parameters and doesn’t return a value, it’s like saying “I want something to happen, but I don’t particularly care how it’s done or what happens to it later.”
  • Functions that accept parameters but don’t return any value do work that changes depending on the arguments, but don’t give anything back.
  • Functions that accept no parameters but return a value do so without needing any extra information.
  • Finally a function that accepts parameters and returns something gives a value back based on the information passed in. It takes all your input suggestions and transforms them into a new output value.
  • When a function does some kind of work that’s unrelated to a return value, like printing to the console, the work is called a side effect. If a function has no return value, all of its work is considered a side effect.

This is a very nice example of what a function can do:

func listByAdding(item: String, toList: String) -> String {
    return toList + "\n" + item
var list = "Milk"
list = listByAdding(item:"Eggs", toList: list)
list = listByAdding(item:"Bread", toList: list)

Hiding complexity is one of the key benefits that using functions brings to your code.

This is hardly a new thing but here it is: the names we see when calling a function (and passing in one or more arguments) are called argument labels. The names used inside the function (the values that have been received) are parameter names.

To declare a parameter without an argument label, we use the underscore _ where the argument label would go. In Swift, the underscore means “I don’t care about this item because I’m not going to use it”.

Now we should open the “Visualization Part 1” playground and complete it.

The “Pie Chart” page was interesting but so buggy: one could easily add proportions that added together to more than 100% and still something would have been drawn… and it would have done so wrong…

The second page, “Chart Key”, instead, was simply not working. Changing the provided code, or even running it … simply failed: no label was ever shown. What the heck is going on here? Same thing said for the third page … nothing is shown when one calls the addKeyItem(withLabel:color:) function. Crazy that this thing could ship with no one checking for it to be correct.

The following page, “Bar Charts”, asked to give values between 0 and 10, but if you put 11 or -2, they are still accepted and rendered… I mean, what’s the point?

The next page again “Bar Chart Customization”, said: “Now you can say what the minimum and maximum values of the charts will be”. The default was between 0 and 100 and guess what? If you tried to input 130 it would accept it, then the playground server would crash and the usable screen would slowly fall down. Incredible how low quality this can be allowed to be! … and unacceptable, as far as I am concerned.

I quickly browsed the next pages and decided to move on. No point in losing (yet) more time on this. A pity, because this chapter was starting to get better.

Wrap up

Good that I came to the end of this chapter.

It was better than the first one, but still very, very far from perfection.

I really wish Apple did less of these things and focused more on its soul, the professionals, the artists, the creatives… Asking people to use iWork without teaching it is really not something that is going to help people become more creative and productive.

End of the episode.

If you like what I’m doing here please consider liking this article and sharing it with some of your peers. If you are feeling like being really awesome, please consider making a small donation to support my studies and my writing (please appreciate that I am not using advertisement on my articles).

If you are interested in my music engraving and my publications don’t forget visit my Facebook page and the pages where I publish my scores (Gumroad, SheetMusicPlus, ScoreExchange and on Apple Books).

You can also support me by buying Paul Hudson’s books from this Affiliate Link.

Anyways, thank you so much for reading!

Till the next one!

Published by Michele Galvagno

Professional Musical Scores Designer and Engraver Graduated Classical Musician (cello) and Teacher Tech Enthusiast and Apprentice iOS / macOS Developer Grafico di Partiture Musicali Professionista Musicista classico diplomato (violoncello) ed insegnante Appassionato di tecnologia ed apprendista Sviluppatore iOS / macOS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: