Share
Explore

Swift Objects and Protocols

Lecture on Swift Objects for iOS App Development

In this session, we will explore the fundamental concepts of objects in Swift, how to create and use them, and understand their importance in building robust and maintainable iOS applications.

Objectives:

Understand the concept of objects in Swift.
Learn how to define and create objects, and apply them to delivering specific algorithms within our Application.
Understand the 4 principles of Object-Oriented Design Patterns:
Encapsulation (protecting state safety)
Inheritance/Abstraction Polymorphism
Practice creating and using objects through progressive code drills.

Here is a comparative chart that highlights the key differences and similarities between Swift classes, structures, and protocols:
Table 1
Feature
Classes
Structures
Protocols
Definition
class
struct
protocol
Instance Creation
Reference type
Value type
N/A (Blueprint)
Memory Management
Reference counting (ARC)
Stack
N/A
Inheritance
Single inheritance
No inheritance
Multiple inheritance (protocol composition)
Reference Semantics
Yes
No
N/A
Value Semantics
No
Yes
N/A
Mutability
Mutability depends on instance
Mutability depends on instance
N/A
Copying Behavior
Reference copied
Data copied
N/A
Initialization
Custom initializers
Custom initializers
Initializers not defined
Deinitialization
Supports deinitializers
No deinitializers
N/A
Encapsulation
Supports access control
Supports access control
Defines required methods and properties without implementation
Extensions
Can be extended
Can be extended
Can be extended
Conformance to Protocols
Yes
Yes
Can inherit from other protocols
Methods
Instance and type methods
Instance and type methods
Method requirements only
Stored Properties
Yes
Yes
No stored properties
Computed Properties
Yes
Yes
Property requirements only
Type Properties
Yes
Yes
N/A
Usage Scenario
Use for complex objects with shared state
Use for simple data structures and when value semantics are desired
Use to define common functionality across different types
There are no rows in this table

Summary of Key Points

Classes are reference types and support inheritance. They are ideal for defining complex objects that share state and require reference semantics.
Structures are value types and do not support inheritance. They are best used for simple data structures and scenarios where value semantics are desired.
Protocols define a blueprint of methods, properties, and other requirements. They are used to define common interfaces and enable polymorphic behavior across different types.

Example Code for Each
Class Example
swift
Copy code
class Person {
var name: String
var age: Int

init(name: String, age: Int) {
self.name = name
self.age = age
}

func displayInfo() {
print("Name: \(name), Age: \(age)")
}
}
Structure Example
swift
Copy code
struct Car {
var make: String
var model: String

func displayInfo() {
print("Car Make: \(make), Model: \(model)")
}
}
Protocol Example
swift
Copy code
protocol Greetable {
var name: String { get }
func greet()
}

class Person: Greetable {
var name: String

init(name: String) {
self.name = name
}

func greet() {
print("Hello, \(name)!")
}
}

struct Animal: Greetable {
var name: String

func greet() {
print("Animal \(name) says hello!")
}
}
Conclusion
Understanding the differences and appropriate use cases for classes, structures, and protocols is essential for writing robust and efficient Swift code. Classes are powerful for complex objects that need reference semantics, structures are excellent for simple data types with value semantics, and protocols provide a flexible way to define shared functionality across different types.

What are Objects in Swift?

The purpose of OBJECTS is to model entities in the real world.
Tangible:
Intangible: relationship

In Swift, objects are instances of classes or structures that encapsulate data and behavior. They are fundamental building blocks for creating complex applications by grouping related properties and methods together.
Objects help in organizing code, promoting reuse, and maintaining a clear separation of concerns.
We will learn to use UML Unified Modeling Language to plan and structure our Objects before writing them.

Key Concepts:

Class and Structure: Both can define objects, but classes have additional features like inheritance and reference semantics.
Properties: Variables or constants defined within a class or structure.
Methods: Functions defined within a class or structure.
Initialization: Process of setting up an object with initial values.

Creating Objects in Swift

Defining a Class

class Person {
var name: String
var age: Int

init(name: String, age: Int) {
self.name = name
self.age = age
}

func displayInfo() {
print("Name: \(name), Age: \(age)")
}
}

Creating an Instance of a Class

let person1 = Person(name: "John Doe", age: 30)
person1.displayInfo() // Output: Name: John Doe, Age: 30

Defining a Structure


struct Car {
var make: String
var model: String

func displayInfo() {
print("Car Make: \(make), Model: \(model)")
}
}

Creating an Instance of a Structure

swift
Copy code
let car1 = Car(make: "Toyota", model: "Camry")
car1.displayInfo() // Output: Car Make: Toyota, Model: Camry

Encapsulation and Inheritance

Encapsulation

Encapsulation is the concept of hiding the internal state of an object and requiring all interaction to be performed through an object's methods.

Example:

class BankAccount {
private var balance: Double = 0.0

func deposit(amount: Double) {
balance += amount
}

func withdraw(amount: Double) {
balance -= amount
}

func getBalance() -> Double {
return balance
}
}

let account = BankAccount()
account.deposit(amount: 1000)
print(account.getBalance()) // Output: 1000.0

Inheritance

Inheritance allows a class to inherit properties and methods from another class.

Example:

swift
Copy code
class Animal {
func sound() {
print("Some generic animal sound")
}
}

class Dog: Animal {
override func sound() {
print("Bark")
}
}

let myDog = Dog()
myDog.sound() // Output: Bark

Progressive Code Drills

Drill 1: Basic Class and Object Creation

Define a class Book with properties for title and author.
Initialize these properties using an initializer.
Create an instance of Book and print its details.
swift
Copy code
class Book {
var title: String
var author: String

init(title: String, author: String) {
self.title = title
self.author = author
}

func displayInfo() {
print("Title: \(title), Author: \(author)")
}
}

let book1 = Book(title: "1984", author: "George Orwell")
book1.displayInfo() // Output: Title: 1984, Author: George Orwell

Drill 2: Encapsulation

Define a class Rectangle with private properties width and height.
Create methods to set and get the dimensions.
Add a method to calculate the area of the rectangle.
swift
Copy code
class Rectangle {
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.