Skip to content
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 {
private var width: Double
private var height: Double

init(width: Double, height: Double) {
self.width = width
self.height = height
}

func setDimensions(width: Double, height: Double) {
self.width = width
self.height = height
}

func getWidth() -> Double {
return width
}

func getHeight() -> Double {
return height
}

func area() -> Double {
return width * height
}
}

let rect = Rectangle(width: 5, height: 10)
print("Area: \(rect.area())") // Output: Area: 50.0

Drill 3: Inheritance

Define a base class Vehicle with a method move.
Create a subclass Bicycle that overrides the move method.
Create instances of both classes and call the move method.
swift
Copy code
class Vehicle {
func move() {
print("The vehicle is moving")
}
}

class Bicycle: Vehicle {
override func move() {
print("The bicycle is pedaling")
}
}

let vehicle = Vehicle()
vehicle.move() // Output: The vehicle is moving

let bike = Bicycle()
bike.move() // Output: The bicycle is pedaling

Drill 4: Using Objects in an iOS App

Create a class User with properties username and email.
Initialize these properties using an initializer.
Use these objects in a simple iOS app to display user information in a label.
swift
Copy code
import UIKit

class User {
var username: String
var email: String

init(username: String, email: String) {
self.username = username
self.email = email
}

func displayInfo() -> String {
return "Username: \(username), Email: \(email)"
}
}

class ViewController: UIViewController {
@IBOutlet weak var userInfoLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
let user = User(username: "johndoe", email: "john.doe@example.com")
userInfoLabel.text = user.displayInfo()
}
}

Summary

In this lecture, we covered the basics of creating and using objects in Swift. We learned how to define classes and structures, encapsulate properties, use inheritance, and integrate these concepts into an iOS app. The progressive drills provided hands-on experience in building and working with objects, laying a strong foundation for further exploration in Swift and iOS app development.

Assignment

Create a class Person with properties firstName, lastName, and a method fullName that returns the full name.
Implement a subclass Student that adds a studentID property and overrides the fullName method to include the student ID.
Create instances of both Person and Student classes and print their full names.
now segue into Protocols : what they are , how they work, how we use them
ChatGPT

Lecture on Swift Protocols

Introduction

In our previous lecture, we discussed Swift objects, how to create them, and how to use them in iOS app development. Today, we'll delve into a powerful feature of Swift called Protocols. Protocols are a fundamental part of Swift programming, enabling us to define blueprints for methods, properties, and other requirements that suit a particular task or piece of functionality.

Objectives

Understand what protocols are in Swift.
Learn how to define and adopt protocols.
Explore the benefits of using protocols.
Practice using protocols through progressive code drills.

What are Protocols?

In Swift, a protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. Protocols can be adopted by classes, structures, and enumerations to provide actual implementations of these requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

Key Concepts

Protocol Definition: Declaring the requirements that conforming types must implement.
Adopting Protocols: Implementing the requirements defined in a protocol.
Protocol Inheritance: Protocols can inherit from other protocols.

Defining a Protocol

Here's a simple example of defining a protocol in Swift:
swift
Copy code
protocol Greetable {
var name: String { get }
func greet()
}

Properties: The protocol defines a property name that must be a String.
Methods: The protocol defines a method greet() that does not return a value.

Adopting a Protocol

To adopt and conform to a protocol, a type must implement all the requirements defined by the protocol.
swift
Copy code
class Person: Greetable {
var name: String

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

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

let person = Person(name: "John")
person.greet() // Output: Hello, John!

Benefits of Using Protocols

Encapsulation: Define what needs to be done without specifying how.
Flexibility: Different types can adopt the same protocol, providing various implementations.
Reusability: Promote code reuse by defining common interfaces.
Polymorphism: Enable polymorphic behavior by using protocol types.

Protocols in Action

Protocol Inheritance

Protocols can inherit from other protocols, adding more requirements on top of the existing ones.
swift
Copy code
protocol Identifiable {
var id: String { get }
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.