How do I conform types to Equatable, Hashable, and Codable in Swift?

In Swift, you can conform your custom types to various protocols like Equatable, Hashable, and Codable to enable value comparison, hashing for collections, and easy encoding/decoding operations, respectively. Below are examples of how you can implement these protocols in your Swift structs or classes.

Equatable

To conform to Equatable, you need to implement the == operator, which compares two instances of your type.

Example:

struct Person: Equatable {
    var name: String
    var age: Int
}

// Example of usage
let person1 = Person(name: "Alice", age: 30)
let person2 = Person(name: "Alice", age: 30)

if person1 == person2 {
    print("They are the same person!")
}

Hashable

To conform to Hashable, you need to provide a hash function. If you're also conforming to Equatable, Swift can automatically synthesize this for you.

Example:

struct Person: Hashable {
    var name: String
    var age: Int
}

// Example of usage
var peopleSet: Set = []
peopleSet.insert(Person(name: "Alice", age: 30))
peopleSet.insert(Person(name: "Bob", age: 25))

print("People in the set: \(peopleSet.count)")

Codable

To conform to Codable, you can simply declare your struct or class as Codable. Swift provides automatic synthesis for properties.

Example:

struct Person: Codable {
    var name: String
    var age: Int
}

// Example of usage
let person = Person(name: "Alice", age: 30)
if let encoded = try? JSONEncoder().encode(person) {
    print("Encoded Person: \(String(data: encoded, encoding: .utf8)!)")
    
    if let decoded = try? JSONDecoder().decode(Person.self, from: encoded) {
        print("Decoded Person: \(decoded)")
    }
}

Equatable Hashable Codable Swift Protocols Swift Structs