Swift TOP 5 Mostly Used Protocols

KD Knowledge Diet
3 min readSep 9, 2024

--

Swift introduces several useful protocols that enhance the flexibility and clarity of your code. These protocols provide a standardized way to define behaviors and relationships between different types. In this article, we’ll explore some of the most valuable protocols in Swift and how they can benefit your development process.

1. Equatable

The `Equatable` protocol allows you to compare instances of a type for equality. By conforming to `Equatable`, you can use the equality operator (`==`) to compare two instances and determine if they are equal.

Example:

struct Point: Equatable {
let x: Int
let y: Int
}
let point1 = Point(x: 1, y: 2)
let point2 = Point(x: 1, y: 2)
if point1 == point2 {
print("The points are equal.")
} else {
print("The points are not equal.")
}

2. Comparable

The `Comparable` protocol builds upon `Equatable` and allows you to establish a total order for your types. By conforming to `Comparable`, you define the relative order of instances, making it possible to use comparison operators like `<`, `<=`, `>`, and `>=`.

Example:

struct Student: Comparable {
let name: String
let grade: Int
static func < (lhs: Student, rhs: Student) -> Bool {
return lhs.grade < rhs.grade
}
}
let alice = Student(name: "Alice", grade: 90)
let bob = Student(name: "Bob", grade: 85)
if alice > bob {
print("\(alice.name) has a higher grade than \(bob.name).")
} else {
print("\(alice.name) has a lower grade than \(bob.name).")
}

3. Hashable

The `Hashable` protocol enables instances of a type to be used as keys in dictionaries and to be stored in sets. Conforming to `Hashable` requires you to provide a hash value (`hash(into:)` method), which Swift uses to efficiently organize and retrieve elements.

Example:

struct City: Hashable {
let name: String
let population: Int
}
let newYork = City(name: "New York", population: 8623000)
let losAngeles = City(name: "Los Angeles", population: 3990000)
var cityPopulations: [City: Int] = [:]
cityPopulations[newYork] = newYork.population
cityPopulations[losAngeles] = losAngeles.population
print(cityPopulations)

4. Codable

The `Codable` protocol simplifies the process of encoding and decoding data to and from various formats, such as JSON and Property Lists. By conforming to `Codable`, your types can be effortlessly serialized and deserialized.

Example:

struct Person: Codable {
let name: String
let age: Int
}
let jsonData = """
{
"name": "Alice",
"age": 30
}
""".data(using: .utf8)!
if let person = try? JSONDecoder().decode(Person.self, from: jsonData) {
print("\(person.name) is \(person.age) years old.")
}

5. CustomStringConvertible and CustomDebugStringConvertible

These protocols allow you to provide custom string representations for your types, improving debugging and readability. By conforming to these protocols, you can customize the output of `description` and `debugDescription` properties.

Example:

struct Book: CustomStringConvertible, CustomDebugStringConvertible {
let title: String
let author: String
var description: String {
return "\(title) by \(author)"
}
var debugDescription: String {
return "Book(title: \(title), author: \(author))"
}
}
let book = Book(title: "The Swift Programming Language", author: "Apple Inc.")
print("Book: \(book)")
print("Debug: \(debugDescription)")

These are just a few of the many protocols that Swift offers to enhance your code. By leveraging these protocols, you can write more expressive, reusable, and maintainable code while benefiting from Swift’s type safety and powerful standard library features.

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!