Swift Language

Overview about the Swift Language

Details
Constants, Variables, and Data Types
1
2
let maximumNumberOfLoginAttemps = 10
var currentLoginAttempt = 0
1
var x = 0.0, y = 0.0, z = 0.0
Type annotations
1
var welcomeMessage: String
Printing constants and variables
1
2
var friendlyWelcome = "Bonjour"
print("The current value of friendlyWelcome is \(friendlyWelcome)")
Semicolons
Most common types in Swift
1
let pi = 3.1415

or

1
let pi: Double = 3.1414
Create your own type
1
2
3
4
5
6
7
8
9
10
import UIKit

struct Car {
    var make: String
    var model: String
    var Year: Int
}

var c = Car(make: "BMW", model: "X3", year: 2022)
print (c.make)
Operators
1
let jedi = "Luke"
1
2
3
4
var opponentScore = 3 * 8
print(opponentscore)
var myScore = 100 / 4
print(myScore)
1
2
3
4
myScore += 3
myScore -= 5
myScore *= 2
myScore /=2
1
2
3
4
let x = 3
let y = 0.1415
let pi = x + y /* not work */
let pi = Double(x) + y

Control Flow

Logical and comparison operators
if and if/else
1
2
3
4
let temperature = 100
if temperature >= 100 {
    print("The water is boiling")
}
1
2
3
4
5
6
7
8
var finished = 2
if finished == 1 {
    print("First place!") 
} else if finished == 2 {
    print("Second place!")
} else {
    print("Third place!")
}
Boolean values
1
2
3
4
var isSnowing = false
if !ifSnowing {
    print("It is not snowing")
}
Switch statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let numberOfWheels = 2
switch numberOfWheels {
    case 0:
        print("Missing wheels!")
    case 1:
        print("Unicycle")
    case 2:
        print("Bicycle")
    case 3:
        print("Tricycle")
    case 4:
        print()"Cars!")
    default:
        print("Too many wheels!")
}
1
2
3
4
5
6
7
let character = "z"
switch character {
    case "a", "e", "i", "o", "u":
        print("Vowels")
    default:
        print("consonant")
}
1
2
3
4
5
6
7
8
9
10
switch distance {
    case 0...9:
        print("It is close")
    case 10...99:
        print("A bit further")
    case 100..999: 
        print("Quite far out")
    default:
        print("Let's call a cab")
}

Exercises

Grade calculation using if-else

Write a Swift program that takes a student’s numerical grade (0 to 100) as input and outputs the corresponding letter grade based on the following criteria:

Template playground code:

1
2
3
4
let grade = 95

//implement if-else logic here

Grade calculation using switch

Write a Swift program that takes a student’s numerical grade (0 to 100) as input and outputs the corresponding letter grade based on the following criteria:

Template playground code:

1
2
3
4
let grade = 95

//implement switch logic here

Grade calculation on app