Swift Syntax 10.2.24
Coming Soon!
Data Types
Int - integer
var age: Int 24;
Float - precision of 6 decimal places
0.82819281927190
Double - precision of 15 decimal places
var percentage: Double = 0.81
String - text
var welcomeMessage: String = "Welcome to the Course!
Bool - boolean type
var isOn: Bool = false
Custom type - using classes
var joe: Person = Person(firstName: "Joe")
Swift has type inference. Swift can infer what type you want without you having to specify the type.
var year = 2024
Variables & Constants
Variables can be changed, but constants cannot be changed.
The following will produce an error
let GRAVITATIONAL_CONSTANT = 9.81
GRAVITATIONAL_CONSTANT = 8.09
let GRAVITATIONAL_CONSTANT = 9.81
var m1 = 20
var m2 = 2000
var r = 5
var F = GRAVITATIONAL_CONSTANT * ((m1*m2)/Int(pow(Double(r), Double(2))))
var width = 0.0, height = 0.0, depth = 0.0
var yourName: String
yourName = "Tutorial Doctor"
var r, g, b: Double
Data Structures
Array
var grocerySet: [Int]
var grocerySet = ['milk','eggs','cheese','bread']
print(grocerySet[0])
grocerySet.append('pizza')
grocerySet.insert('water', at: 2)
grocerySet.sort()
grocerySet.reverse()
grocerySet.shuffle()
Set
A set is unordered and cannot have duplicate values. Better performance because you don't have to search a whole array for a value because there are no duplicates. So looking up a value is constant time.
var grocerySet: Set<Int> = []
You can cast an array to a set. The duplicated values will be removed.
var grocerySet = Set(groceryList)
grocerySet.insert('ham')
grocerySet.contains('pizza')
print(grocerySet)
Dictionary
Dictionaries have constant time lookup like sets.
// A dictionary of words and their associated definitions
let wordDictionary: [String: String] = [
"a": "the first letter of the english alphabet",
"aa": "basaltic lava having a rough, broken surface",
"aaa": "a small battery that is used in small electronic devices",
]
print(wordDictionary["a"])
Statements
var name = "TutorialDoctor"
print(name)
//Semicolon required for same-line statements
let cat = "🐱"; print(cat)
Assertions, Preconditions Optionals
Conditional Statements
If, Else If, Else
var cakeTemperature = 80
if cakeTemperature == 100{
print("Take the cake out of the oven")
}
else if cakeTemperature < 100{
print("Leave the cake in the oven")
}
else{print("The cake is still heating up")}
Switch
For switch statements, you have to handle all cases.
var cakeTemperature = 80
switch cakeTemperature {
case 100:
print("Take the cake out of the oven")
case ..<100:
print("Take the cake out of the oven")
default:
print("The cake is still heating up")
}
Loops
for i in 0...6{
print(i)
}
for i in 0..<6{
print(i)
}
Use an underscore if you aren't using the iterator in the loop.
var randomIntArray: [Int] = []
for _ in 0..<15{
let randomInteger = Int.random(in: 0...100)
randomIntArray.append(randomInteger)
}
print(randomIntArray)
let names = ["robert","susan","joe","cynthia"]
for name in names{
print(name)
}
For-In Loop While Loop Repeat-While Loop
Functions
func add(number1: Int, number2: Int) -> Int{
return number1 + number2
}
print(add(number1: 2,number2: 3))
To make the code more readable you can use an argument label. The argument label is used when calling the function (at the call site).
func add(number1: Int, to number2: Int) -> Int{
return number1 + number2
}
print(add(number1: 2, to: 3))
to
is the argument label (external label) , and number2
is a parameter label (internal label). to
could be called whatever you want. If you don't have an argument label, the parameter label will be used.
Closures
A closure is like an anonymous function (arrow function) in Javascript.
A simple closure
var greet = { print("Welcome") }
greet()
Passing parameters to a closure.
let greeting = { (place: String) in
print("Welcome to \(place)")
}
greeting("America")
Return information from a closure
let greetingMessage = { (place: String) -> String in
return "Welcome to \(place)"
}
print(greetingMessage("India"))
Passing a closure to a function
let notifyUser = { print("You are all done!") }
func processPayment(lastStep: () -> Void){
print("Taking your payment")
print("Processing your payment")
lastStep()
}
processPayment(lastStep: notifyUser)
Macros
Enums
An enum (enumeration) is a group of related values. Enums help you avoid errors using strings and gives you autocomplete
enum Direction{
case north
case east
case south
case west
}
You can list values on a single line.
enum Direction {case north, east, south, west}
enum DayOfWeek{
case sunday
case monday
case tuesday
case wednesday
case thursday
case friday
case saturday
}
enum DayOfWeek{
case sunday
case monday
case tuesday
case wednesday
case thursday
case friday
case saturday
}
func getHours(on day: DayOfWeek){
if day == .sunday{
print(20)
}
}
getHours(on: .sunday)
enum WeatherCode: String{
case L = "Drizzle"
case R = "Rain"
case RW = "Rain Showers"
case RS = "Rain/snow mix"
}
func getWeatherDescription(for code: WeatherCode){
print(code.rawValue)
}
getWeatherDescription(for: .L)
getWeatherDescription(for: .R)
getWeatherDescription(for: .RS)
Classes
?
means the attribute is optional.
class Vehicle{
var doors: Int?
var wheels: Int?
var has_an_engine: Bool?
var color: String?
var type: String?
init(){}
init(type: String){
self.doors = 4
self.wheels = 4
self.has_an_engine = true
self.color = ""
self.type = type
}
func start(){
print("\(type) is starting")
}
func stop(){
print("\(type) is stopping")
}
}
let nissan = Vehicle(type: "Sedan")
nissan.type
nissan.start()
nissan.stop()
let accord = Vehicle() // uses empty init
accord.type = "Benz"
accord.start()
accord.stop()
Inheritance
class WaterVehicle: Vehicle{
var mass: String?
func float(){
print("Floating \(self.type)")
}
// you can override methods
override func start(){
print("\(type) starting to run on water")
}
}
let boat = WaterVehicle()
boat.type = "Submersible"
boat.start()
boat.float()
Structures, Enumerations, Generics, Protocols, Subscripts, Extensions, Optional Chaining
Structs
A struct is a value type while a class is a reference type.
The example below shows that a class is a reference type, and setting an object to another object that is a class and changing a value changes both objects' data.
var car = Vehicle()
var hoopty = car
hoopty.type = "Hoopty"
print(car.type)
A struct on the other hand allows each instance to be unique.
Structs have a memberwise initializer so you don't have to create an initializer function
struct Vehicle{
var doors: Int?
var wheels: Int?
var has_an_engine: Bool?
var color: String?
var type: String?
}
Extensions
Extensions allow you to extend a type with additional functionality. Extensions are project wide, so every item will get extended. Subclasses only apply to a subclass.
import UIKit
extension String{
func removeWhitespace() -> String{
return components(separatedBy: .whitespaces).joined()
}
}
let alphabet = "A B C D E F G"
print(alphabet.removeWhitespace())
Access Control
Modules, Packages, Source Files
Files
Jobs
Other
Integers, Int, Uint, Floating Point Numbers, Type Safety, Numeric Literals, Numeric Type Conversion, Integer Conversion, Type aliases, Booleans, Tuples, Optionals, nil,