Don’t Panic! iOS Basic Coding — iOS #4

icons from icons8.com, one of my fave sites ever!

As said on the front of the Hitch Hiker’s Guide to the Galaxy, Don’t Panic! It’s time to learn some code, but it’s ok, we’ll take it easy to begin with, with some basics. Let’s start right at the beginning …

What exactly is code?

Code is the “programming language” you use in your apps to specify certain things. Things like — what happens when a button is pressed, what happens when an image is swiped to the left, what colour text to use, which font to use, how long it takes to do something … and much much more.

Why can’t we just use English?

Interesting question — as yet no-one has (to my knowledge) created a system where you can just use natural language to build apps. Each app platform / system / operating system has a programming language that’s been created to allow you to build apps using a specific set of commands. For iOS the main language used was Objective-C. A few years ago, Apple brought out Swift, a new, theoretically better language. You can still build apps in Objective-C, but this course will use Swift, as it’s the future! And round these parts, we’re all about The Future!

So, I need to learn a new language?

Sort of. A programming language isn’t like a natural language, like French or Irish; it’s really a set of commands, structures and concepts that can be used to do particular tasks.

Like a natural language however, you don’t need to learn it all to begin to use use it. A child can say “I don’t want my dinner” years before she can say “Once matter passes a black hole’s event horizon, it won’t escape, not even light”.

Likewise, you can make basic iOS apps without becoming completely proficient in Swift or Objective-C. Over time, with more practice and learning, you can become more “fluent” in the language and create more complex apps.

Really, not even light will escape?

Nevermind that, focus! But yes …

Ok, back to the coding

We’ll go through some of the basics, then put them into action in Xcode to give them a bit more context.

Coding is generally made up of these basic blocks:

  • Classes
  • Variables
  • Functions

There are way more things apart from those, but they’ll do for now.

Classes / Objects

A lot of programming languages, including Swift are “Object-Orientated” — this means it’s all about Objects; or as they’re otherwise called, Classes.

A Class is basically a way of describing a “thing” or an “object” — a thing that is in the app; a thing you can use or do something with or to. For example, each “Screen” in an iOS app is a “UIViewController” Class that can do various things — like displaying content like text, images or buttons.

Furthermore, each of those content items are themselves Classes; there is a UIButton Class for buttons, a UILabel Class for displaying text etc and many many many (many many) more classes to avail of and use.

“Behind” the screen, there are also Classes to use and manipulate data / content / other objects— such as the “String” class, which is used to store and manipulate natural language e.g. a name or a title.

Most of “learning to code” is learning about these Classes are and how they can be used.

There are two main sets of Classes to learn — the Swift ones and the iOS SDK ones. “SDK” means Software Development Kit — it’s a set of Classes and Functions (written in Swift) that Apple have pre-made to help you make apps. The UIViewController, UIButton and UILabel Classes mentioned above all come from the iOS SDK.

We’ll go through loads of these Classes through the various tutorials.

What’s the benefit of Objects / Classes?

Classes are a really handy way of doing things in code; they allow the definition of concepts in an understandable manner. What makes this even handier is that you can define your own Classes. If the app is about cars, you can create a Car Class. If it’s about airplane times, you can create an Airplane Class and maybe an Airport Class too, along with a Departure Class and an Arrival Class.

Classes also allow for re-use of code. If you have 10 names to display, you just need 10 instances of the one Class, not 10 different ones. If you have 7,853 airplanes, then you just need one Airplane Class.

Variables

Variables are how you use Classes. A variable is an “instance” of a Class, that you can use to store a value and re-use in your code. So:

var myName : String = "Odysseus"

This is actual Swift code to create (or “declare”) a variable, of type (Class) String and to “initialise” it with a value of “Odysseus”. (If you were cool enough to have a name like that).

var

is how you say variable

myName 

is the name of the variable, and it could be anything, like:

var yourName

or

var whatever

would also be fine.

: String

says that the variable is of type / Class “String” and

= "Odysseus"

stores that value in the variable. If you then typed:

print(myName)

in your app in Xcode, and “ran” the app, you’d see “Odysseus” in the output area. (More on that later)

What is the “print” however?

print

This is a function — the next fundamental block of coding.

Functions

Functions are groups of code that “do” something. The print function above is a built-in function that you can use to print out values of variables to Xcode- this is handy when building apps so you can keep track of what’s going on.

Swift has many many built in functions — again, a lot of learning to code is learning what these are and how to use them.

You can (and will) also create your own functions. Here’s a simple function to add two numbers and “return” the result:

func addTwoNumbers(number1: Int, number2: Int)->{
return number1 + number2
}

The

func

says that this is a function.

addTwoNumbers

is the name. Again, we could have called this anything.

(number1 : Int, number2: Int)

is a bit more complicated. number1 and number2 are “paramaters”. Parameters are values we can “pass in” to functions for use inside them. Here we we say that there are two parameters in this function, both of Class “Int” — which is used to store numbers.

Again “number1” and “number2” are the names of the parameters, we could have called them anything.

->Int

is how we specify that the function will “return” a value of Class Int.

{

is known as an “opening bracket” and signifies that the function’s code is about to begin. This code is what “runs” when the function is “called” i.e. “run”.

return number1 + number2

adds the two numbers together and “returns” the result. Returns means that this is the result of the function.

}

is the “closing bracket”. Every opening bracket must have a corresponding closing one. Or all hell breaks loose!

How would you use this amazing function?

var twoNumbersAdded = addTwoNumbers(10, 10)

This creates a variable called “twoNumbersAdded” and stores in it the value 20 (the result of our function adding 10 and 10 together).

Cool? Confusing? It’s ok, all will become clearer with more examples and time!

A better example

Create an app in Xcode and open the ViewController.swift file.

the standard ViewController.swift

The “viewDidLoad” and the “didReceiveMemoryWarning” are both functions. Note neither have the “->” bit — this means they don’t return values, they just do their bit of code without returning a result.

Let’s create our own function and “call” it when the app is run. Before the final “closing bracket” in the file, type this:

func changeScreenColor(){
self.view.backgroundColor = UIColor.blue
}

This creates a function that will change the color of the main “view” in the ViewController. The “view” is actually an instance of UIView, another Class.

Now, in this function (which runs more or less immediately when the app is run):

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

add this line, before the closing bracket:

changeScreenColor()

i.e.

code added to change the main view’s color

This “calls” our function. Now run the app and you should see:

blue!

Yes! You just made something in an app change, using a function!

Let’s try out a couple more things. Add this new function which has a return type:

func getAwesomeName()->String{
return “Cohen the Barbarian”
}

and then add this lines to viewDidLoad to use the function:

let name : String = getAwesomeName()print(name)

so the full code looks like:

import UIKitclass ViewController: UIViewController {   override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib. changeScreenColor() let name : String = getAwesomeName()
print(name)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getAwesomeName()->String{
return "Cohen the Barbarian"
}
func changeScreenColor(){
self.view.backgroundColor = UIColor.blue
}
}

Run the app and the output should be in Xcode:

Let’s add one more function, this time with parameters:

func getBalance(name: String)->Int{
if name == "Commander Vimes" {
return 100
}else{
return 200
}
}

and call it in viewDidLoad:

let balance = getBalance(name: "Granny Ogg")print(balance)

Run the app and you should see:

The 200 is shown as the parameter we supplied was not equal to “Commander Vimes”. In fairness though, who would be?!

Summary

This post skimmed the tip of the iceberg of coding in Swift, but we all need to start somewhere. We’ll introduce more coding concepts gradually as we go along, so keep an eye out for the upcoming tutorials and guides!

This is part of appsandbiscuits — my new site to help teach app development to people with zero coding experience. If you liked it, please hit the little heart below, it’ll help other people come across the site! Thanks! Andy.

--

--

--

Creator of Boxapopa, the iOS game for young kids with zero ads, just fun! https://apps.apple.com/ie/app/boxapopa/id1550536188

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Microsoft CRM Data Migration Tool — Data2CRM.Migration

Firestore Backups the easy way with Cloud Workflows

Firestore Backups the easy way with Cloud Workflows

Drawbacks of AWS Code build

Creating AWS API Gateway With Private EndPoint Using Terraform

Image encoding

How To Install Jenkins on Ubuntu 20.04

How We Ran a Hackathon Remotely

5 Super Easy Values to Assess your Organization’s DevOps Readiness

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Andy O'Sullivan

Andy O'Sullivan

Creator of Boxapopa, the iOS game for young kids with zero ads, just fun! https://apps.apple.com/ie/app/boxapopa/id1550536188

More from Medium

Swift — Cocoapods Usage

Swift questions and answers part -III

Fundamental Design Pattern: Delegation

UserDefaults Unit testing in iOS