ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Swift Tutorial• 7 min read

Protocols & Protocol-Oriented Programming (POP)

Interfaces in Swift, default implementations via extensions, and Codable

Swift is fundamentally a Protocol-Oriented language. Protocols define blueprints of methods and properties, while protocol extensions provide default implementations.

Protocol-Oriented Architecture & Codable

Protocols define contracts: protocol Identifiable { var id: String { get } }.

Protocol Extensions: Provide default method implementations so conforming types don't have to re-implement shared logic.

Codable: A protocol composition (Encodable & Decodable) that automatically converts Swift structs to/from JSON with zero manual parsing code!

Parsing JSON with the Codable Protocol
import Foundation

// Automatically decodable from JSON!
struct Course: Codable {
    let title: String
    let lessonCount: Int
    let isCertified: Boolean
}

let jsonString = """
{"title": "Swift Concurrency", "lessonCount": 10, "isCertified": true}
"""

let jsonData = jsonString.data(using: .utf8)!
let course = try JSONDecoder().decode(Course.self, from: jsonData)

print("Decoded Course: \(course.title), Lessons: \(course.lessonCount)")
Codable synthesizes JSON serialization and deserialization automatically.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which built-in Swift protocol enables automatic serialization and deserialization of structs to and from JSON?