Instruction 2

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Protocol-Oriented Programming

Protocol-Oriented Programming is a design pattern that enables you to abstract implementation details across various components of your app. It’s commonly used to separate concerns in your code, such as decoupling UI logic from data logic.

protocol BookRepository {
    func getBooks() async throws  -> [Book]
    func createBook(_ book: Book) async throws
}
// 1
struct APIBookRepository: BookRepository {
    // Define URLs...

    // 2
    func getBooks() async throws -> [Book] {
        // 3
        let (data, _) = try await URLSession.shared.data(from: booksURL)
        return try JSONDecoder().decode([Book].self, from: data)
    }
    
    // 4
    func createBook(_ book: Book) async throws {
        // 5
        let data = try JSONEncoder().encode(book)
        // 6
        var request = URLRequest(url: createBookURL)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = data
        // 7
        _ = try await URLSession.shared.data(for: request)
    }
}
See forum comments
Download course materials from Github
Previous: Demo 1 Next: Demo 2