DEV Community

Tawhid
Tawhid

Posted on • Updated on

Learn Swift with me

Swift is a programming language for developing apps for IOS and Mac OS, and it is destined to become the foremost computer language in the mobile and desktop space.Made to replace Objective-C.Swift code can communicate with obj-c but provides a better readable syntax.

Objective-C Hello world:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

   NSLog (@"hello world");
   [pool drain];
   return 0;
}
Enter fullscreen mode Exit fullscreen mode

Swift Hello World:

var str = "Hello, World!"
print(str)
Enter fullscreen mode Exit fullscreen mode

Pretty easy compared to obj-c right?
Let's get into it:

Installing:

You need swift installed in your machine to run swift code.
You can download it from: here

Swift Variables, Constants and Literals

Variables:
A variable is a container to hold data.
In swift, we use the var keyword to declare a variable and it is dynamic that means you do not need to assign datatypes but you can if you want to.

var name = "Rick"
print(name)
//output: rick
Enter fullscreen mode Exit fullscreen mode

Assign Datatypes to Variables

var siteName: String
siteName = "dev.to"
print(siteName) 
Enter fullscreen mode Exit fullscreen mode

You can assign datatypes by : type.For example: number: Int name: String .

Variables names must start with either a letter, an underscore _, or the dollar sign $. For example,

// valid
var a = "hello"
var _a = "hello"
var $a = "hello"
//invalid
var 1a = "hello"
Enter fullscreen mode Exit fullscreen mode

Swift is case-sensitive. So A and a are different variables. For example,

var A = 5 
var a = 55
print(A) // 5
print(a) // 55
Enter fullscreen mode Exit fullscreen mode

Swift Constants
A constant is a special type of variable whose value cannot be changed. For example,

let x = 80
x = 60
print(x)
//error
main.swift:4:1: error: cannot assign to value: 'x' is a 'let' constant
Enter fullscreen mode Exit fullscreen mode

Avoid using reserved keywords[String, for etc] for variable names

Swift Literals
Literals are representations of fixed values in a program. They can be numbers, characters, or strings, etc. For example, "Hello, World!", 12, 23.0, "C", etc.

Literals are often used to assign values to variables or constants.

print("This is a hardcoded string or a literal")
Enter fullscreen mode Exit fullscreen mode

Literal Examples:

//string
let someString: String = "Swift is fun" 
//unicode characters
let someCharacter: Character = "S"
//boolean
let pass: Bool = true  
//floating point
let piValue: Float = 3.14
Enter fullscreen mode Exit fullscreen mode

There are four types of integer literals in Swift:

Type Example Remarks
-Decimal 5, 10, -68 Regular numbers.
-Binary 0b101, 0b11 Start with 0b.
-Octal 0o13 Start with 0o.
-Hexadecimal 0x13 Start with 0x.

DataTypes:

Float : 5.4
Int : 5
Character : A
String : Hi
Double  27.7007697012432
Bool true/false
Enter fullscreen mode Exit fullscreen mode

Swift Basic Input and Output:

print("Swift is powerful")

// Output: Swift is powerful
Enter fullscreen mode Exit fullscreen mode

Here, the print() function displays the string enclosed inside the double quotation.

Syntax of print()

In the above code, the print() function is taking a single parameter.

However, the actual syntax of the print function accepts 3 parameters

print(items: separator: terminator:)
Here,

items - values inside the double quotation
separator (optional) - allows us to separate multiple items inside print().
terminator (optional) - allows us to add add specific values like new line "\n", tab "\t"

print() with terminator:

// print with terminator space
print("Good Morning!", terminator: " ")

print("It's rainy today")
Output

Good Morning! It's rainy today
Enter fullscreen mode Exit fullscreen mode

Notice that we have included the terminator: " " after the end of the first print() statement.

Hence, we get the output in a single line separated by space.

print() with separator
print("New Year", 2022, "See you soon!", separator: ". ")
Output

New Year. 2022. See you soon!
In the above example, the print() statement includes multiple items separated by a comma.

Notice that we have used the optional parameter separator: ". " inside the print() statement. Hence, the output includes items separated by . not comma.

concatenated strings:
print("one" + "two")

Print Variables and Strings together:

var year = 2014
print("Swift was introduced in \(year)")
Enter fullscreen mode Exit fullscreen mode

-Text: Swift was introduced in
-Variable: /(year)

To take inputs in swift we use readLine()

print("Enter your favorite programming language:")
let name = readLine()

print("Your favorite programming language is \(name!).")
Enter fullscreen mode Exit fullscreen mode

Comments

//single line comments

/*multi line
comments*/
Enter fullscreen mode Exit fullscreen mode

Optional

How to declare an Optional?
You can simply represent a Data type as Optional by appending ! or ? to the Type. If an optional contains a value in it, it returns value as Optional, if not it returns nil.

Example 1: How to declare an optional in Swift?

var someValue:Int?
var someAnotherValue:Int!
print(someValue)
print(someAnotherValue)
Enter fullscreen mode Exit fullscreen mode

Operators:

Terninary

You can replace this code

// check the number is positive or negative
let num = 15
var result = ""

if (num > 0) {
     result = "Positive Number"
}
else {
     result = "Negative Number"
}

print(result)
Enter fullscreen mode Exit fullscreen mode

with

// ternary operator to check the number is positive or negative
let num = 15

let result = (num > 0) ? "Positive Number" : "Negative Number"
print(result)

Enter fullscreen mode Exit fullscreen mode

Bitwise

Here's the list of various bitwise operators included in Swift

Operators Name Example
& Bitwise AND a & b
| Bitwise OR a | b
^ Bitwise XOR a ^ b
~ Bitwise NOT ~ a
<< Bitwise Shift Left a << b

Bitwise Shift Right a >> b

Flow Control:

If else:

let number = 10

// check if number is greater than 0
if (number > 0) {
  print("Number is positive.")
}

print("The if statement is easy")

Enter fullscreen mode Exit fullscreen mode

if else

Switch:

a better approach of if else.

Example:

switch (expression)  {
  case value1:
    // statements 

  case value2:
    // statements 

  ...
  ...

  default:
    // statements
}

Enter fullscreen mode Exit fullscreen mode

switch

Applied Example:

// program to find the day of the week 

let dayOfWeek = 4

switch dayOfWeek {
  case 1:
    print("Sunday")

  case 2:
    print("Monday")

  case 3:
    print("Tuesday")

  case 4:
    print("Wednesday")

  case 5:
    print("Thursday")

  case 6:
    print("Friday")

  case 7:
    print("Saturday")

  default:
    print("Invalid day")
}
Enter fullscreen mode Exit fullscreen mode

LOOP
a loop is a piece of code that will continue running until one or more value is as given.
for in:

for val in sequence{
  // statements
}
Enter fullscreen mode Exit fullscreen mode

loop

Example: Loop Over Array

// access items of an array 
let languages = ["Swift", "Java", "Go", "JavaScript"]

for language in languages {
      print(language)
}
Enter fullscreen mode Exit fullscreen mode

for Loop with where Clause
In Swift, we can also add a where clause with for-in loop. It is used to implement filters in the loop. That is, if the condition in where clause returns true, the loop is executed.

// remove Java from an array

let languages = ["Swift", "Java", "Go", "JavaScript"]

for language in languages where language != "Java"{
  print(language) 
}
Enter fullscreen mode Exit fullscreen mode

Swift while Loop
Swift while loop is used to run a specific code until a certain condition is met.

The syntax of while loop is:

while (condition){
  // body of loop
}
Enter fullscreen mode Exit fullscreen mode

Here,

-A while loop evaluates condition inside the parenthesis ().
-If condition evaluates to true, the code inside the while loop is executed.
-condition is evaluated again.
-This process continues until the condition is false.
-When condition evaluates to false, the loop stops.

while

Example 1: Swift while Loop

// program to display numbers from 1 to 5

// initialize the variable
var i = 1, n = 5

// while loop from i = 1 to 5
while (i <= n) {
  print(i)
   i = i + 1
}
Enter fullscreen mode Exit fullscreen mode

Guard:

Syntax of guard Statement
The syntax of the guard statement is:

guard expression else {
  // statements
  // control statement: return, break, continue or throw.
}
Enter fullscreen mode Exit fullscreen mode

Here, expression returns either true or false. If the expression evaluates to

true - statements inside the code block of guard are not executed
false - statements inside the code block of guard are executed
Note: We must use return, break, continue or throw to exit from the guard scope.
Example:

var i = 2

while (i <= 10) {

  // guard condition to check the even number 
  guard i % 2 == 0 else {

     i = i + 1
    continue
  }

  print(i)
  i = i + 1
} 
Enter fullscreen mode Exit fullscreen mode

The break statement is used to terminate the loop immediately when it is encountered.
The continue statement is used to skip the current iteration of the loop and the control flow of the program goes to the next iteration.

Array:
Array is a data structure that holds multiple data altogether

// an array of integer type
var numbers : [Int] = [2, 4, 6, 8]

print("Array: \(numbers)")  
Enter fullscreen mode Exit fullscreen mode

Access Array Elements
In Swift, each element in an array is associated with a number. The number is known as an array index.

We can access elements of an array using the index number (0, 1, 2 …). For example,

var languages = ["Swift", "Java", "C++"]

// access element at index 0
print(languages[0])   // Swift

// access element at index 2
print(languages[2])   // C++
Enter fullscreen mode Exit fullscreen mode

Add Elements to an Array
Swift Array provides different methods to add elements to an array.

  1. Using append()

The append() method adds an element at the end of the array. For example,
array.append(2)

  1. Using insert()

The insert() method is used to add elements at the specified position of an array. For example,

array.insert(2, at: 1)

SET:

Create a Set in Swift
Here's how we can create a set in Swift.

// create a set of integer type
var studentID : Set = [112, 114, 116, 118, 115]

print("Student ID: \(studentID)")
Enter fullscreen mode Exit fullscreen mode

specify type of set:
var studentID : Set<Int> = [112, 114, 115, 116, 118]
-remove() - remove an element
-insert() - insert a value
-removeFirst() - to remove the first element of a set
-removeAll() - to remove all elements of a set
sorted() sorts set elements
forEach() performs the specified actions on each element
contains() searches the specified element in a set
randomElement() returns a random element from the set
firstIndex() returns the index of the given element

Dictionary:

var capitalCity = ["Nepal": "Kathmandu", "Italy": "Rome", "England": "London"]
print(capitalCity)
Enter fullscreen mode Exit fullscreen mode

Add Elements to a Dictionary
We can add elements to a dictionary using the name of the dictionary with []. For example,

var capitalCity = ["Nepal": "Kathmandu", "England": "London"]
print("Initial Dictionary: ",capitalCity)

capitalCity["Japan"] = "Tokyo"

print("Updated Dictionary: ",capitalCity)
print(capitalCity["Japan"])
Enter fullscreen mode Exit fullscreen mode

Dictionary Methods
Method Description
sorted() sorts dictionary elements
shuffled() changes the order of dictionary elements
contains() checks if the specified element is present
randomElement() returns a random element from the dictionary
firstIndex() returns the index of the specified element
removeValue() method to remove an element from the dictionary

Tuple:

Create A Tuple
In Swift, we use the parenthesis () to store elements of a tuple. For example,

var product = ("MacBook", 1099.99)
Here, product is a tuple with a string value Macbook and integer value 1099.99.
Enter fullscreen mode Exit fullscreen mode

Like an array, each element of a tuple is represented by index numbers (0, 1, ...) where the first element is at index 0.

We use the index number to access tuple elements. For example,

// access the first element
product.0

// access second element
product.1
// modify second value
product.1 = 1299.99
Enter fullscreen mode Exit fullscreen mode

In Swift, we can also provide names for each element of the tuple. For example,

var company = (product: "Programiz App", version: 2.1)
company.product //access it
Enter fullscreen mode Exit fullscreen mode

Functions:

A function is a block of code that performs a specific task.

Suppose we need to create a program to create a circle and color it. In this case, we can create two functions:

a function to draw the circle
a function to color the circle
Hence, a function helps us break our program into smaller chunks to make our code reusable and easy to understand.

In Swift, there are two types of function:

User-defined Function - We can create our own functions based on our requirements.
Standard Library Functions - These are built-in functions in Swift that are available to use.
Let's first learn about user-defined functions.

Swift Function Declaration
The syntax to declare a function is:

func functionName(parameters)-> returnType {
  // function body 
}
Enter fullscreen mode Exit fullscreen mode

Here,

func - keyword used to declare a function
functionName - any name given to the function
parameters - any value passed to function
returnType - specifies the type of value returned by the function
Let's see an example,

func greet() {
print("Hello World!")
}
Enter fullscreen mode Exit fullscreen mode

Here, we have created a function named greet(). It simply prints the text Hello World!.

This function doesn't have any parameters and return type. We will learn about return type and parameters later in this tutorial.

Calling a function in Swift
In the above example, we have declared a function named greet().

func greet() {
  print("Hello World!")
}
Enter fullscreen mode Exit fullscreen mode

Now, to use this function, we need to call it.

Here's how we can call the greet() function in Swift.

// call the function
greet()
Enter fullscreen mode Exit fullscreen mode

Working of Recursion in Swift

func recurse() {
  ... ...  
  recurse()
  ...  ...     
}
Enter fullscreen mode Exit fullscreen mode

recurse()
Here, the recurse() function is calling itself over and over again. The figure below shows how recursion works.

func

In Swift, a closure is a special type of function without the function name. For example,

{
  print("Hello World")
}
Enter fullscreen mode Exit fullscreen mode

Here, we have created a closure that prints Hello World.

Before you learn about closures, make sure to know about Swift Functions.

Swift Closure Declaration
We don't use the func keyword to create closure. Here's the syntax to declare a closure:

{ (parameters) -> returnType in
   // statements
}
Enter fullscreen mode Exit fullscreen mode

Here,

parameters - any value passed to closure
returnType - specifies the type of value returned by the closure
in (optional) - used to separate parameters/returnType from closure body

// declare a closure
var greet = {
  print("Hello, World!")
}

// call the closure
greet()
Enter fullscreen mode Exit fullscreen mode

If I try to cover OOP in this blog it will be a lot large
so I will make a seperate blog about this .
Buy me a coffee

Top comments (6)

Collapse
 
dumboprogrammer profile image
Tawhid

yea,In native apps the only reason to use swift is "It is easy" but I prefer Obj-c because in obj-c you have much control over what is done.

Collapse
 
siddev profile image
Siddhant Jaiswal

I want to get into Mobile App development and I guess Swift might be it.
But will i able to install swift on windows machine? I guess not, Though I'm planning to buy iPad but I don't know if I'll be able to code on that ?

The only other option is installing a MacOS VM and that is too much work for me at least. Hence Flutter seems a more viable option until and unless I'm able to use Swift on Windows or iPad.

Please guide me. πŸ˜…

Collapse
 
dumboprogrammer profile image
Tawhid • Edited

Although, you can install swift in your windows machine but for making apps for the Apple ecosystem you need Xcode which is Macos ONLY IDE.
but you can get Swift playground on your ipad which will make developing apps sophisticated but you cannot compile it to an ios app.So you can develop using Swift in an ipad but macos in the vm is always a viable option.

Collapse
 
imsteph profile image
Stefano Rigato

You can code on iPad with Swift Playground, Apple recently released it, though I don't know if there's any limitation compared to xCode on MacOS.

Collapse
 
jack94507501 profile image
Jack

Very intresting post

Collapse
 
dumboprogrammer profile image
Tawhid

Thanks