ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Swift Programming Tutorial: A Quick Introduction Of Essentials

Updated on September 7, 2017
geekinbluejeans profile image

Is a Resource Speaker, AI Ethicist, Linux System Administrator, Computer Programmer, and Appreneur.

Swift Logo by Apple Inc.
Swift Logo by Apple Inc.


Since Apple announced that Swift was made open-source, I can’t help but to start loving this programming language (Don’t worry Python, you will always be my first love). As a proof that I already love this programming language, my applications in the App Store was created in Swift.

This article covers the basic stuff in order for you to dive into this young but very promising programming language.


Important: This tutorial is not recommended if you have zero knowledge in programming concepts. I designed this tutorial for those with little or expert coding knowledge, who wants the quickest way on understanding Swift.


Important facts about Swift:

- Developed by Apple Inc.

- Designed by Chris Lattner.

- General Purpose and multi-paradigm programming language.

- Open Source

- Created for iOS, macOS, watchOS, tvOS, and Linux.

- Popularly used for creating iPhone Apps and iPad Apps.


Since I don’t like long introductions, lets move on right away to the basics of swift.


How to get Swift for macOS?

The easiest way to get swift for macOS is by installing Xcode from the App Store. Simple as that.


How to get Swift for Linux?

For Linux, Ubuntu distribution is the best choice if you want a smooth sailing installation.

Unfortunately, this tutorial doesn’t cover installing swift on Linux, since it takes a separate tutorial to cover that. Don’t worry, swift.org provides detailed documentation on how to install it on Linux platform.


Important: Please take note that you need to be familiar with Terminal Commands if you are going to use Linux. Else, you will find it hard to both install and run swift.



Before we begin...

We are going to use the amazing Playground in Xcode. To create one, choose File -> New -> Playground, then choose a name for your Playground. Now it doesn’t matter what platform you are going to choose since we are dealing with foundations of swift.

If you are using Linux, any text editor will do. Personally, I use atom.io or vim editor for Linux platform.


“Hello World” as usual

A programming tutorial will never be complete without “Hello World”. This section will teach you on how to basically run a swift code. So let’s go straight into it.


Type below code in Playground or text editor.

print("Hello World")

If you are using Playground, it will automatically show the output after typing the code.


For Linux users, follow below instructions:

1. Save your file with .swift extension.

E.g.

HelloWorld.swift

2. Change the file permission to executable by running chmod 750 file.swift.

E.g.

chmod 750 HelloWorld.swift

3. You can run un-compiled swift code by executing terminal command swift file.swift.

E.g.

swift HelloWorld.swift


To compile a swift code in Linux, execute terminal command swiftc file.swift -o CompiledCodeName.

E.g.

swiftc HelloWorld.swift -o HelloWorld

Where HelloWorld.swift is the code that you saved with .swift extension, and HelloWorld is the compiled file. It is not required to name the compiled file HelloWorld. Feel free to name it whatever filename you like.


To run a compiled swift code, execute command ./CompiledCodeName.

E.g.

./HelloWorld


By the way, the process for running swift on Linux can also be executed on macOS Terminal.


Swift Variables

Variables are used to store data. You can easily assign variables by declaring it using var as keyword.

E.g.

var firstVar = "Hello World"
print(firstVar)

The output will be:

Hello World

In above example, you declare firstVar as variable containing the value “Hello World”.


The variable value can be changed by assigning newer value.

E.g.

var firstVar = "Hello World"
firstVar = "Hi Earth"
print(firstVar)

The output will be:

Hi Earth


You can also declare multiple variables by using comma:

var firstVar = "Hello World", secondVar = "Hi Earth", thirdVar = “Hey Planet”

It is also valid to declare it like this:

var firstVar = "Hello World", 
secondVar = "Hi Earth", 
thirdVar = “Hey Planet”


Swift Constant

Constants are used to store data that cannot be changed. We use the keyword let to declare a constant.

E.g.

let firstVar = "Hello World"
print(firstVar)

The output will be:

Hello World


Again, you cannot change the value of a constant once it is declared.


Swift Data Types

Data Type are the different kinds of value that you can store in either variables or constants.

Below are the basic data types of swift:

- String

- Character

- Integer

- Float

- Double

- Bool


We use colon after declaring a variable to use data type.

E.g.

var firstVar: String = "Hello World"
print(firstVar)

Same example, but we insert colon and String to declare the data type of firstVar.


Data Type: String

String can store multiple number of characters and unicode in hexadecimal.

E.g.

let firstVar: String = "HELLO WORLD"
let uniString: String = "H\u{400}LLO WORLD"
print(firstVar)
print(uniString)

The output will be:

HELLO WORLD

HЀLLO WORLD


Data Type: Character

Character from the word itself, is used to store single character. It can also store unicode in hexadecimal.

E.g.

let anyChar: Character = "A"
let anyUnicode: Character = "\u{100}"
print(anyChar)
print(anyUnicode)

The output will be:

A

Ā


Data Type: Integer

Integer store whole numbers that can be positive or negative. This includes zero by the way.

E.g.

var numberOne: Int = 1
var numberTwo: Int = 2
var numberThree: Int = numberOne + numberTwo
print("One plus Two is equal to", numberThree)

The output will be:

One plus Two is equal to 3


Note: There are several variants of integer. To name a few: Int32, Int64, Uint,etc... You use these variants to adjust the range of your Integer. You may check the official swift documentation for more details.


Data Type: Float

Float store numbers with decimal point or fraction.

E.g.

let anyWithDecimal: Float = 100.19
let half: Float = 1/2
print(half)
print(anyWithDecimal * half)

The output will be:

0.5

50.095


Note: 0.0 is the default value of Float.


Data Type: Double

Double also store numbers with decimal point and fraction but with larger range.

E.g.

let anyWithDecimal: Float = 99.999999999999
let anyFraction: Float = 1/9
print(anyFraction)
print(anyWithDecimal * anyFraction)

The output will be:

0.111111

11.1111


Data Type: Bool

Bool has only 2 values: True or False.

E.g.

let fact: Bool = true
let fiction: Bool = false
let combineFactFiction = fact && fiction
print("Can we mix fact and fiction to tell the truth?", combineFactFiction)

The output will be:

Can we mix fact and fiction to tell the truth? false


See! Even the computer itself knows that you cannot mix fact and fiction at the same time to tell the truth.


Swift Comments

Comments are ignored by interpreters or compilers while they start reading the source code. It is used to put notes or readable explanation together with the source code.


Use // to declare single line comment.

E.g.

//Declare a variable
var firstVar = "Hello World"
//prints the declared variable
print(firstVar)


Use /* */ to declare multi line comment

E.g.

/* These lines are ignored
var firstVar = "Hello World"
firstVar = "Hi Earth"
print(firstVar)
*/


Swift Basic Operators

Operators are single or multiple symbols that can perform a specific action.

Below are the basic swift operators:

- Assignment

- Arithmetic

- Comparison

- Range

- Logical



Assignment Operators

Basically, an assignment operator assign values from left operand to its right operand. The symbol for assignment operator is =.

In case you haven’t notice yet, we are already using assignment operators from the moment we are declaring variables or constants. But for your benefit, here is another example.

E.g.

let one = 1
let ten = 10
let eleven = one + ten
print(eleven)


There is also what we call Compound Assignment Operators that combines = with another operators.

E.g.

var number = 1
number += 2
print(number)

The output will be:

3


Arithmetic Operators

Arithmetic are the first operators that we learned in math which is add, subtract, multiply, and divide. In swift, those mentioned operators are still the same. Below are the arithmetic operators:

Addition +

Subtraction -

Multiplication *

Division /

Remainder %

Note: In other programming language, remainder operator is commonly known as modulo operator.

E.g.

print(1 + 1) //Addition example
print(10 - 5) //Subtraction example
print(2 * 3) //Multiplication example
print(20 / 4) //Division example
print(20 % 3) //Remainder example

The output will be:

2

5

6

5

2


Comparison Operators

This operator compare values of left operand to its right operand.

Below are the comparison operators:

- Equal to ==

- Not equal to !=

- Greater than >

- Less than <

- Greater than or equal to >=

- Less than or equal to <=


When a comparison operator is used, the result will either be true or false.

E.g.

print(1 == 1) //Equal to example
print(10 != 5) //Not equal to example
print(2 > 3) //Greater than example
print(20 < 4) //Less than example
print(20 >= 3) //Greater than or equal to example
print(30 <= 30) //Less then or equal to example

The output will be:

true

true

false

false

true

true


Range Operators

This operator is used as shortcut for expressing range of values.

The most commonly used range operator is Closed Range operator which uses ... to declare.

E.g.

for range in 1...3 {
  print("\(range) multiply by 5 is \(range * 5)")
}

The output will be:

1 multiply by 5 is 5

2 multiply by 5 is 10

3 multiply by 5 is 15


The other one is called Half-Open Range which uses ..< to declare.

E.g.

for range in 1..<3 {
  print("\(range) multiply by 5 is \(range * 5)")
}

The output will be:

1 multiply by 5 is 5

2 multiply by 5 is 10


You will notice the difference between two range operators by looking at their output.


Logical Operators

It’s all about Logical AND, Logical OR, and Logical NOT. Below are the symbols that they represent:

- Logical AND &&

- Logical OR ||

- Logical NOT !

Logical operator also involves boolean values True and False.

E.g.

print(true && false) //AND example
print(false || true) //OR example
print(!true) //NOT exmaple

The output will be:

false

true

false


Wait! There is more about operators

Yup, we are not yet done with operators. There are still more to discuss.

Going back, operators are either Unary, Binary, or Ternary operators.


Unary Operators appear before or after their target.

E.g.

!a

-1

-two

a!


Binary Operators appear in between their two targets.

E.g.

1 + 1

3 – 2

4 * 6

10 / 5


Ternary Operators is a conditional operator with three targets. Its syntax is Condition ? True : False. This means that it returns True if condition is met and False if not.

E.g.

print(1 == 1.0 ? "They are equal": "They are not equal")

The output will be:

They are equal


Ternary operators is also a shorthand if-else statement which will be discussed later. Below is its equivalent in if-else statement which will also return the same output.

if 1 == 1.0 {
  print("They are equal")
} else {
  print("They are not equal")
}


String Interpolation

This topic sounds florid, but it is not complicated as you think it is. Interpolation is all about inserting variables or constants inside the string.

E.g.

var country: String = "Philippines"
let capital: String = "Manila"
print("The capital of \(country) is \(capital)")

The output will be:

The capital of Philippines is Manila


You can also insert variables and constant by using comma.

E.g.

let capital: String = "Manila"
print("We are currently working in", capital)

The output will be:

We are currently working in Manila


String Concatenation

Concatenation means joining strings or characters together.

E.g.

let hello = "Hello"
let world = "World"
let conStr = hello + world
print(conStr)

The output will be:

HelloWorld


Swift Optionals

An optional can have a value or not. Simple as that.

E.g.

let firstName: String = "Bruce"
let lastName: String = "Wayne"
let superHeroName: String? = "Batman"
print(superHeroName)

The output will be:

Optional("Batman")

We declare an optional by using ? after a data type.


This is an example of an optional without a value.

E.g.

let superHeroName: String? = nil
print(superHeroName)

The output will be:

nil

Note: The word nil means nothing.


To remove the optional word in the output, force unwrap it using exclamation mark.

E.g.

let superHeroName: String? = "Batman"
print(superHeroName!)

The output will be:

Batman

Important: Use force unwrap if you are 100% sure that there is a value. You will not like the result if you force unwrap a nil. You will get Fatal Error! That’s what I mean.


To avoid fatal error, you can write your optional code like this:

E.g.

let superHeroName: String? = "Batman"
superHeroName != nil ? print(superHeroName!) : print("Not a superhero")

In the above code, we use a ternary operator to prevent nil from force unwrap.


Swift Arrays

Arrays are variables that holds multiple values.

E.g.

var numbers = [1,2,5,9]
var progLang = ["Swift", "Python", "C++", "JavaScript"]
print(numbers)
print(progLang)

The output will be:

[1, 2, 5, 9]

["Swift", "Python", "C++", "JavaScript"]


As best practice, you can also specify the data type of your arrays.

E.g.

var numbers: [Int] = [1,2,5,9]
var progLang: [String] = ["Swift", "Python", "C++", "JavaScript"]


Extracting specific values can be done like this:

E.g.

var progLang: [String] = ["Swift", "Python", "C++", "JavaScript"]
print(progLang[1])
print(progLang[2])
print(progLang[3])
print(progLang[0])

The output will be:

Python

C++

JavaScript

Swift

To explain it further, values in an array starts with 0. So string Swift is 0, Python is 1, C++ is 2, and JavaScript is 3.


You can also add values to an already declared array.

E.g.

var progLang: [String] = ["Swift", "Python", "C++", "JavaScript"]
progLang.append("Kotlin")
print(progLang)

The output will be:

["Swift", "Python", "C++", "JavaScript", "Kotlin"]



Swift Dictionaries

Dictionaries are like Arrays but lets you access values based on a key that you specify.

E.g.

var revealName = [
  "Batman": "Bruce",
  "Superman": "Clark",
  "Wonder Woman": "Diana",
  "Green Lantern": "Hal",
  "Flash": "Barry",
  "Aquaman": "Arthur",
  "Martian Manhunter": "J'onn"
]
print(revealName["Superman"]!)

Note: You can also declare an Array using this format and vice versa. Also, values inside dictionary are not in order so you cannot use indexing from Array. Finally, ! means optional that will be discussed later.

Going back, the output will be:

Clark


You can add more values to a dictionary by doing this:

E.g.

revealName["Green Arrow"] = "Oliver"

Edit an existing values by also doing the same thing.

E.g.

revealName["Flash"] = "Wally"

When you print the result again, you will notice that Oliver is also added and Barry changes to Wally.


Again, it is a good practice to declare data types on your dictionary.

E.g.

var numberWords: [Int:String] = [1: "One", 5: "five", 10: "Ten", ]


Swift Sets

Aside from Arrays and Dictionaries, we can also store multiple values via sets. To differentiate a set from an array or dictionary, here is a simple description of a set.

- Un-ordered list (just like dictionary).

- It doesn’t use key on values (just like array).

- Cannot have the same values twice.

E.g.

var comicChar: Set<String> = ["Batman", "Robin", "Flash", "Atom"]
var numberSam: Set<Int> = [1, 3, 5, 9]

Based on above example, a set is declared on data type part.


I know you won’t appreciate the use of sets unless we give a good example. For our first illustration, we are going to combine 2 sets using union.

E.g.

var listChar1: Set<String> = ["Batman", "Robin", "Flash", "Atom"]
var listChar2: Set<String> = ["Robin", "Flash", "Oracle", "Cyborg"]
let combList: Set<String> = listChar1.union(listChar2)
print(combList)

The output will be:

["Batman", "Cyborg", "Robin", "Atom", "Oracle", "Flash"]

As I mentioned, a set cannot have the same value twice. So don’t expect 2 “Flash” and “Robin” from the combined set.


Same values from 2 different sets can be detected by using intersection.

E.g.

var listChar1: Set<String> = ["Batman", "Robin", "Flash", "Atom"]
var listChar2: Set<String> = ["Robin", "Flash", "Oracle", "Cyborg"]
let sameValue: Set<String> = listChar1.intersection(listChar2)
print(sameValue)

The output will be:

["Flash", "Robin"]


You can also used the same values for the purpose of removal by using subtracting.

E.g

var listChar1: Set<String> = ["Batman", "Robin", "Flash", "Atom"]
var listChar2: Set<String> = ["Robin", "Flash", "Oracle", "Cyborg"]
let delValue: Set<String> = listChar1.subtracting(listChar2)
print(delValue)

The output will be:

["Batman", "Atom"]

Above example means that it will show the values of listChar1 except “Robin” and “Flash” that also exist on listChar2.


Swift Conditional (Decision Making)

Swift Decision Making performs specific action when certain conditions are met.

Forms of conditionals are the following:

- if statement

- if ... else statement

- if ... else if ... else statement

- switch statement


if statement

The word if is the most basic conditional statement.

E.g.

var gameScore: Int = 100
if gameScore == 100 {
  print("Perfect")
}

The output will be:

Perfect

When you translate the above conditional into human language: If gameScore is equal to 100, then print Perfect.


if ... else statement

How about if the value doesn’t met the programmed condition? The best thing to do, is to use else to avoid unwanted errors.

E.g.

var gameScore: Int = 99
if gameScore == 100 {
  print("Perfect")
} else {
  print("You didn't achieve the perfect score")
}

The output will be:

You didn't achieve the perfect score

In this example, else action was triggered because the gameScore didn’t reach 100.


if ... else if ... else statement

In reality, you will not only rely on 2 choices to trigger an action. You will be needing multiple choices. Using else if will make it possible.

E.g.

var gameScore: Int = 50
if gameScore == 100 {
  print("Perfect")
} else if gameScore >= 80 {
  print("Average")
} else if gameScore >= 50 {
  print("Below Average")
} else if gameScore >= 20 {
  print("Beginner")
} else {
  print("Not in range")
}

The output will be:

Below Average

To make things clear, you use else as default action when nothing meets the programmed condition.


Switch statement

There will be situations that you will be needing more organize alternative to if ... else if ... else statement for larger numbers of possible conditions.

E.g.

var gameScore: Int = 85
switch gameScore {
case 100:
  print("Perfect")
case 80...99:
  print("Average")
case 50...79:
  print("Below Average")
case 20...49:
  print("Beginner")
default:
  print("Not in range")
}

The output will be:

Average


Nested statement

You can also put any if statement or case statement inside any if statement or case statement and vice versa. That practice is called nested.

E.g.

var gameScore: Int = 24
switch gameScore {
case 100:
  print("Perfect")
  if gameScore == 100 {
    print("You are qualified for the next level")
  }
case 80...99:
  print("Average")
case 50...79:
  print("Below Average")
case 20...49:
  print("Beginner")
  if gameScore <= 25 {
    print("Game Over")
  }
default:
  print("Not in range")
}

The output will be:

Beginner

Game Over


Swift Loops

There will be situations that you need to repeat some actions in your code. Your first instinct will always be to copy and paste the code multiple times. But doing it is not the best practice. Good thing there is what we called Loop to take care of this situation.

A Loop repeats a block of code for as long as the condition is met. Basically, swift uses for loop and while loop.


for loop

The for loop repeats a block of code based on the range of values that you have given.

E.g.

var fellowOfRing = [
  "Frodo",
  "Sam",
  "Merry",
  "Pippin",
  "Aragorn",
  "Boromir",
  "Legolas",
  "Gimli",
  "Gandalf"
]
for member in fellowOfRing {
  print("\(member) is a member of Fellowship of the Ring")
}

The output will be:

Frodo is a member of Fellowship of the Ring

Sam is a member of Fellowship of the Ring

Merry is a member of Fellowship of the Ring

Pippin is a member of Fellowship of the Ring

Aragorn is a member of Fellowship of the Ring

Boromir is a member of Fellowship of the Ring

Legolas is a member of Fellowship of the Ring

Gimli is a member of Fellowship of the Ring

Gandalf is a member of Fellowship of the Ring

So instead of printing each names multiple times, we use for loop to make our code better.


while loop

In while loop, it repeats a block of code until the conditions are met.

E.g.

var countOneToTen = 0
while countOneToTen <= 10 {
  print("Number:", countOneToTen)
  countOneToTen += 1
}

The output will be:

Number: 0

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

Number: 6

Number: 7

Number: 8

Number: 9

Number: 10


Swift Functions

Function is a reusable code that performs specific task. Just like loops, one goal of using a function is to avoid writing the same block of code with the same purpose multiple times.

To declare a function, we use the word func.

E.g.

func raceHobbit() {
  print("The Hobbits are peaceful.")
}
raceHobbit()

The output will be:

The Hobbits are peaceful.


You can customize your function by using a parameter (argument), so that you can have some different results.

E.g.

func raceHobbit(hobbitName: String) {
  print("The Hobbits are peaceful.")
  print(hobbitName, "is a Hobbit")
}
raceHobbit(hobbitName: "Bilbo")

The output will be:

The Hobbits are peaceful.

Bilbo is a Hobbit


There will be situations that a more readable and clear parameter is useful, especially when you are dealing with large amount of data. In below example, we are going to use halfling as external parameter of hobbitName.

E.g.

func raceHobbit(halfling hobbitName: String) {
  print("The Hobbits are peaceful.")
  print(hobbitName, "is a Hobbit")
}
raceHobbit(halfling: "Bilbo")


You can use _ if you don’t want to use any external name at all.

E.g.

func raceHobbit(_ hobbitName: String) {
  print("The Hobbits are peaceful.")
  print(hobbitName, "is a Hobbit")
}
raceHobbit("Bilbo")


It is also necessary to have a mandatory returning values for some situations. In below example, we are going to create a pound to kilogram converter.

E.g.

func lbsToKilogram(lbs: Float) -> Float {
  let kg = lbs * 0.453592
  print("\(kg)kg")
  return kg
}
lbsToKilogram(lbs: 200)

The result will be:

90.7184kg


Swift Enums

Shorthand for enumerations. Enums lets you customize data type and its values inside.

To appreciate the usefulness of enums, let’s take look at below example.

E.g.

var fellowRace: String = "Aragorn"
switch fellowRace {
case "Aragorn": print("Human")
case "Legolas": print("Elf")
case "Gimli": print("Dwarf")
case "Frodo": print("Hobbit")
default: print("N/A")
}

The output will be:

Human

Code above obviously works fine. But there will be situations that you might misspell “Aragorn” to “Aragon”. Mistyping things will not be good in real situation where you are dealing with enormous lines of code. One way to prevent it, is by customizing your data types and values by using enums.

E.g.

enum fellowRace: String {
  case Aragorn, Legolas, Gimli, Frodo
}
var identifyRace: fellowRace = .Aragorn
switch identifyRace {
case .Aragorn: print("Human")
case .Legolas: print("Elf")
case .Gimli: print("Dwarf")
case .Frodo: print("Hobbit")
}

We start declaring enumeration by using the word enum. Using enum means that Swift will only accept the customize values inside. This practice will make our code more organize and lesser prone to errors.


Raw values can also be placed in enums for more customization.

E.g.

enum fellowRace: String {
  case Aragorn = "Human"
  case Legolas = "Elf"
  case Gimli = "Dwarf"
  case Frodo = "Hobbit"
}
var identifyRace: fellowRace = .Aragorn
print(identifyRace.rawValue)


Swift Structs

Shorthand for structures. Structs is another way of customizing data types and values by using properties or methods.

E.g.

struct weapons {
  var primary: String
  var secondary: String
}
var aragorn: weapons = weapons(primary: "Sword", secondary: "Dagger")
var legolas: weapons = weapons(primary: "Bow", secondary: "Knives")
print(aragorn.primary)
print(legolas.secondary)

The output will be:

Sword

Knives

From our first example, var primary and var secondary are called properties. Struct properties are simply variables inside structs that will represent the values. With the use of structs, we can now easily require aragorn and legolas to have primary and secondary weapons. And your code is much better and organize this way than using variables for each values.


Structs also has function like feature that is called method.

E.g.

struct weapons {
  var primary: String
  var secondary: String
  func whatWeapon() {
    print("Primary weapon: \(self.primary)")
    print("Secondary weapon: \(self.secondary)")
  }
}
var legolas: weapons = weapons(primary: "Bow", secondary: "Knives")
legolas.whatWeapon()

The output will be:

Primary weapon: Bow

Secondary weapon: Knives


Swift Class

Class is the most common approach to Object Oriented Programming in Swift. We use the keyword class in order to represent an object. For this section of tutorial, you are going to learn the following:

- initialization

- properties

- methods

- inheritance


As you notice, class is very similar to struct but both have some important differences.

For the rest of tutorial regarding class, we are going to create an object containing different superpowers as example.


Class Properties

Class Properties are variables or constants inside a class.

E.g.

class SuperPowers {
  let powerOne: String = "Super Strength"
  let powerTwo: String = "Super Speed"
  let powerThree: String = "Flight"
  var numberOfPowers: Int = 3
}
var showPower = SuperPowers()
print(showPower.powerThree)

The output will be:

Flight

In our above example, we use properties to declare different types of superpowers. Then in order to show one of those superpowers, we call the SuperPowers class in a variable then one of its properties.


Class Methods

Class Methods are functions inside a class.

E.g.

class SuperPowers {
  let powerOne: String = "Super Strength"
  let powerTwo: String = "Super Speed"
  let powerThree: String = "Flight"
  var numberOfPowers: Int = 3
  func learnNewPowers(NewPower new: String) -> String {
    var learnedPower = new
    return new
  }
}
var superPowers = SuperPowers()
var newPower = superPowers.learnNewPowers(NewPower: "Heat Vision")
print("I learned", newPower)

The output will be:

I learned Heat Vision

In this example, we give our object SuperPowers the method to learn new abilities via func learnNewPowers.


Class Initializing

Initializing or also known as init is a method that automatically runs when a class is called. We use keyword init to declare it.

E.g.

class SuperPowers {
  let powerOne: String = "Super Strength"
  let powerTwo: String = "Super Speed"
  let powerThree: String = "Flight"
  var numberOfPowers: Int
  init(NumberOfPowers num: Int) {
    self.numberOfPowers = num
    print(numberOfPowers, "powers so far.")
  }
}
var superPowers = SuperPowers(NumberOfPowers: 3)

The output will be:

3 powers so far.

It automatically printed the number of powers once class is called and parameter was indicated.


Class Inheritance

In actual situation, you may need to create multiple classes. But some of them may have some same properties or methods. Now to avoid writing the same properties and methods again, inheritance will come into play.

Inheritance is all about using properties and methods from other class. The source class is called Super Class, and the one inheriting the properties and methods of super class is called Sub Class.

For our inheritance example, we are going to grant superpowers to a person.

E.g.

class SuperPowers {
  let powerOne: String = "Super Strength"
  let powerTwo: String = "Super Speed"
  let powerThree: String = "Flight"
  var numberOfPowers: Int = 3
  init() {
    print("Superpowers granted")
  }
  func learnNewPowers(NewPower new: String) -> String {
    var learnedPower = new
    return new
  }
}
class Person: SuperPowers {
  let knownQuality: String = "Brave"
}
var newHero = Person()
print("Our new hero is", newHero.knownQuality)

The output will be:

Superpowers granted

Our new hero is Brave

Above example shows that the subclass Person use its own method knownQuality while using init from superclass SuperPowers.


We can also edit the existing method from superclass for customization. This can be done by using override.

E.g.

class Person: SuperPowers {
  let knownQuality: String = "Brave"
  override init() {
    super.init()
    print("This person is now a superhero")
  }
}
var newHero = Person()

The output will be:

Superpowers granted

This person is now a superhero


Using override, we can still use the init from superclass with some modification. Same procedure applies for methods, just use override func.



This is the end of my quick tutorial regarding the essentials of Swift programming language. Although it only covers the basics, knowing it will give you one step closer to creating your dream application.



- Arc


© 2017 Arc Sosangyo

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)