Swift Cheatsheet



The Swift Cheatsheet provides a quick reference to Swift language concepts from basic to advance level. This is very useful for iOS developers and students who are preparing for interviews and exams. Go through this cheat sheet and learn the concept of theSwift programming language.

Table of Content

  1. Variables and Constants
  2. Data Types
  3. Operators
  4. String Manipulation
  5. Comments
  6. If-Else Statements
  7. Switch Statements
  8. Loops (for, while, repeat-while)
  9. Function Basics
  10. Function Parameters and Return Values
  11. Default Parameters
  12. Variadic Parameters
  13. Closures
  14. Arrays
  15. Dictionaries
  16. Sets
  17. Tuples
  18. Optional Binding
  19. Nil Coalescing Operator
  20. Optional Chaining
  21. Classes and Structures
  22. Properties and Methods
  23. Inheritance
  24. Initialization
  25. Deinitialization
  26. Protocol Basics
  27. Protocol Conformance
  28. Extensions
  29. Protocol Extensions
  30. Generics
  31. Error Handling
  32. Enumerations
  33. Type Casting
  34. Automatic Reference Counting (ARC)
  35. Weak and Unowned References
  36. Higher-Order Functions (map, filter, reduce)
  37. SwiftUI Basics
  38. Property Wrappers
  39. Pattern Matching

1. Variables and Constants

Variables and constants store values. Variables can be changed after initialization, while constants cannot.

 var strName = "Tutorialspoint" // Mutable let constName = 5 // Immutable print(strName) print(constName) 

2. Data Types

Swift supports data types like Int, Double, String, and Bool.

 var age: Int = 55 var pi: Double = 3.1456 var varBool: Bool = true var str_var: String = "Tutorialspoint!" print(age) print(pi) print(varBool) print(str_var) 

3. Operators

Operators perform operations on variables and values.

 // Addition let sum = 5 + 3 // Subtraction let subtract = 10 - 2 // Multiplication let mul = 4 * 3 // Division let quotient = 10 / 2 // Modulus let remainder = 10 % 3 print("Addition : ", sum) print("Subtraction : ", subtract) print("Multiplication : ", mul) print("Quotient : ", quotient) print("Remainder : ", remainder) 

4. String Manipulation

String manipulation is the process of modifying, analyzing, or changing the sequence of characters.

 let name = "Swift Programming" // Concatenation let varConcat = "Hello, " + name // Interpolation let varInterpolar = "Hello, \(name)!" print(name) print(varConcat) print(varInterpolar) 

5. Comments

Comments are ignored by the compiler and are used for blocks of code.

 // This is a single-line comment /* This is a multi-line comment */ 

6. If-Else Statements

If-else statements are used to set the condition based on the code block.

 let age = 18 if age <= 18 { print("You are eligible for vote.") } else { print("You are not eligible for vote.") } 

7. Switch Statements

Switch statements match a value against multiple cases.

 let str = "Tutorialspoint" switch str { case "text": print("This is a text.") case "Tutorialspoint": print("This is Tutorialspoint.") default: print("Unknown") } 

8. Loops (for, while, repeat-while)

Loops are used to execute a block of code multiple times.

for-in loop

The for-in loop determines the repetition of a specific code block.

 import Foundation for number in 1...5 { print("Result: \(number)") } 

while loop

The while loop runs the code block as long as a specified condition is true.

 var i = 1, n = 4 // while loop from i = 1 to 5 while (i <= n) { print(i) i = i + 1 } 

repeat-while

The repeat-while is similar to the while loop. The block of repeat is executed before the test expression.

 var cnt = 1 repeat { print("Count is \(cnt)") cnt += 1 } while cnt <= 5 

9. Function Basics

Functions encapsulate reusable blocks of code.

 func greet() { print("Hello, World!") } greet() 

10. Function Parameters and Return Values

Functions can take parameters and return values. Below is the implementation −

 func sum(x: Int, y: Int) -> Int { return x + y } let res = sum(x: 5, y: 6) print(res) 

11. Default Parameters

Default parameters provide default values to function arguments/parameters.

 func fun(name: String = "Tutorialspoint") { print("Hello, \(name)!") } fun() // default parameters fun(name: "Mark") 

12. Variadic Parameters

Variadic parameters accept zero or more values of a specified type.

 func sum(num: Int...) -> Int { return num.reduce(0, +) } let result = sum(num: 1, 2, 3, 4, 5) print(result) 

13. Closures

Closures are defined using self-contained blocks of functionality that can be passed around and used in the program.

 let message = { (name: String) -> String in return "Hello, \(name)!" } print(message("Tutorialspoint")) 

14. Arrays

Arrays store ordered collections of values of the same type.

 var num = [11, 12, 13, 14, 15] num.append(20) print(num) 

15. Dictionaries

Dictionaries are defined using key-value pairs.

 var capitalCountry = ["India": "New Delhi", "Japan": "Tokyo"] capitalCountry["France"] = "Paris" print(capitalCountry) 

16. Sets

Sets store unique values and does not maintain a specific order.

 var uniNum: Set = [1, 2, 3, 4, 5] uniNum.insert(6) print(uniNum) 

17. Tuples

Tuples groups are sets of multiple values into a single value.

 let data = (empName: "Tapas", company: "Tutorialspoint") print("Name: \(data.empName), Company: \(data.company)") 

18. Optional Binding

Optional binding is the process of checking whether an option has a value and using it if it does.

 var name_str: String? = "Tutorialspoint" if let name = name_str { print("Welcome to, \(name)!") } else { print("Name is nil.") } 

19. Nil Coalescing Operator

The nil coalescing operator guarantees that an optional contains a value.

 let defaultName = "Welcome to Hyderabad" let name: String? = nil print("Hello, \(name ?? defaultName)!") 

20. Optional Chaining

Optional chaining is used to call the properties, methods, and subscripts on optionals.

 class P { var r: R? } class R { var rooms = 1 } let p = P() if let count = p.r?.rooms { print("The residence has \(count) room(s).") } else { print("Not retrieve the number of rooms.") } 

21. Classes and Structures

In Swift, classes and structures are the building blocks of the programming language. Here, we have some references to understand better−

  • Classes are referred to by the reference types whereas structures are value types.
  • Classes support inheritance while structures do not.
  • Classes have deinitializers while structures do not.

Defining a class

 class Person { var name: String var age: Int init(name: String, age: Int) { self.name = name self.age = age } func description() -> String { return "\(name) is \(age) years old." } } let person = Person(name: "Mark", age: 25) print(person.description()) 

Defining a structure

 struct Point { var x: Int var y: Int func distance(to point: Point) -> Double { let dx = Double(point.x - x) let dy = Double(point.y - y) return (dx * dx + dy * dy).squareRoot() } } 

22. Properties and Methods

Properties and methods allow users to add the functionality of the classes and structures. In Swift, properties store values and methods to define behavior.

 class Circle { var r: Double // radius var c: Double { // circumference return 2 * 3.14159 * r } init(r: Double) { self.r = r } func area() -> Double { return 3.14159 * r * r } } let circle = Circle(r: 5) print("Circumference: \(circle.c)") print("Area: \(circle.area())") 

23. Inheritance

Inheritance allows a user to create a class that inherits the properties and methods of another class.

 class Vehicle { var speed: Int init(speed: Int) { self.speed = speed } func description() -> String { return "Traveling at \(speed) km/h" } } class Car: Vehicle { var brand: String init(speed: Int, brand: String) { self.brand = brand super.init(speed: speed) } override func description() -> String { return "\(brand) car traveling at \(speed) km/h" } } let car = Car(speed: 120, brand: "Toyota") print(car.description()) 

24. Initialization

In Swift, initialization is the process of creating an instance of a class, structure, or enumeration.

 struct Emp { var name: String var id: Int // Custom initializer init(name: String, id: Int) { // set the properties self.name = name self.id = id } } // Create an instance of Emp using the initializer let result = Emp(name: "Raj", id: 25) print("Name: \(result.name), ID: \(result.id)") 

25. Deinitialization

Deinitialization is the process to clean up an instance of a class. This is denoted by the keyword deinit.

 class myFile { var fName: String init(fName: String) { self.fName = fName print("FileHandler for \(fName) is initialized.") } // Deinitializer deinit { print("FileHandler for \(fName) is being deinitialized.") } } // Create and release an instance var handler: myFile? = myFile(fName: "text_file.txt") // call the deinitializer handler = nil 

26. Protocol Basics

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. This is similar to the classes, structures, and enumeration.

 protocol SomeProtocol { // protocol definition } 

27. Protocol Conformance

Protocol conformance is defined using the blueprint of methods, properties, and other requirements for tasks or functionalities.

 protocol fun { var name: String { get } func greet() } struct Person: fun { var name: String func greet() { print("Hello, my name is \(name).") } } let person = Person(name: "Tom") person.greet() 

28. Extensions

Extensions allow users to add new functionality to existing classes, structures, enumerations, or protocols.

 extension Int { func square() -> Int { return self * self } } let number = 5 print("Square of \(number) is \(number.square())") 

29. Protocol Extensions

Protocol extensions enable users to add functionality to conforming types without requiring explicit implementation in each type.

 protocol Describable { var description: String { get } } extension Describable { func describe() { print(description) } } struct Car: Describable { var description: String } let car = Car(description: "A red sports car") car.describe() 

30. Generics

Generics provide a way to write flexible and reusable code for types that meet certain requirements. Below is the example of swap values of two variables −

 func swapValues<T>(_ a: inout T, _ b: inout T) { let temp = a a = b b = temp } var first = "Hello" var second = "World" swapValues(&first, &second) print("First: \(first), Second: \(second)") 

31. Error Handling

Error handling is the process of responding and recovering from the error that occurs in the program.

 do { // the code which throw an error try expression // If no error is thrown, this block is execute } catch error_1 { // handling specific error_1 } catch error_2 { // handling specific error_2 } catch { // Handle any other errors } 

32. Enumerations

In Swift, enum is the short form of enumeration, which is the user-defined data type for a fixed set of related values.

 // define enum enum Person { // define enum values case x, y, z } // create enum variable var res: Person // assign value to enum variable res = Person.x print("Result:", res) 

33. Type Casting

The type casting is a process to change the type of the class.

 // Integer to String let num: Int = 42 // Type casting integer to string let numStr = String(num) print("The string value is: \(numStr)") print("Type of numberString: \(type(of: numStr))") // String to Float let nStr: String = "25" // Type casting string to float if let val = Float(nStr) { print("Integer value: \(val)") print("Type of ageInt: \(type(of: val))") } else { print("Invalid") } 

34. Automatic Reference Counting (ARC)

In Swift, automatic reference counting is used to manage the memory of class instances. It automatically keeps track of strong references to objects and deallocates them when no strong references remain.

 class Person { var name: String init(name: String) { self.name = name print("\(name) is initialized") } deinit { print("\(name) is deinitialized") } } var person1: Person? = Person(name: "TONY") var person2 = person1 // Person is not deallocated because person2 still holds a strong reference person1 = nil // Now the Person instance is deallocated person2 = nil 

35. Weak and Unowned References

To prevent strong reference cycles, Swift provides weak and unowned references. These references do not increase the reference count of an instance.

 class Owner { var name: String var car: Car? init(name: String) { self.name = name } } class Car { var brand: String // Prevents strong reference cycle weak var owner: Owner? init(brand: String) { self.brand = brand } } var john: Owner? = Owner(name: "John") var tata: Car? = Car(brand: "TATA") john?.car = tata tata?.owner = john // Both instances are deallocated john = nil 

36. Higher-Order Functions (map, filter, reduce)

Higher-order functions like map, filter, and reduce enable you to manipulate collections in a functional programming.

 let numbers = [1, 2, 3, 4, 5] // map() let squared = numbers.map { $0 * $0 } print(squared) // filter{} let evenNumbers = numbers.filter { $0 % 2 == 0 } print(evenNumbers) // reduce() let sum = numbers.reduce(0) { $0 + $1 } print(sum) 

38. SwiftUI Basics

SwiftUI is an Apple declarative framework for building user interfaces across all Apple platforms. It is used to define the UI components.

 import SwiftUI struct ContentView: View { var body: some View { VStack { Text("Tutorialspoint!") .font(.title) .padding() Button(action: { print("Button tapped") }) { Text("Click Here") .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } } } } 

39. Property Wrappers

Property wrappers add additional behavior to properties, such as data storage or validation.

 @propertyWrapper struct NonNegative { private var value: Int var wrappedValue: Int { get { value } set { value = max(0, newValue) } } init(wrappedValue: Int) { self.value = max(0, wrappedValue) } } struct Account { @NonNegative var balance: Int } var account = Account(balance: 100) print(account.balance) account.balance = -50 print(account.balance) 

40. Pattern Matching

In Swift, pattern matching is a popular feature that allows users to match values against patterns. It is commonly used in switch statements, but it can also be used in loops and conditional statements.

 let number = 5 switch number { case 1: print("One") case 2...4: print("Between two and four") case let x where x > 4: print("Greater than four: \(x)") default: print("None of the above") } let coordinates = (x: 0, y: 0) switch coordinates { case (0, 0): print("Origin") case (let x, 0): print("On the X-axis at \(x)") case (0, let y): print("On the Y-axis at \(y)") case let (x, y): print("At point (\(x), \(y))") } 
Advertisements
close