Type-Safe Supabase Queries with CodingKeys for snake_case
Implementing the Teacher Dashboard Enrollment Service for our Music Theory Learning app, we ran into a common Swift backend challenge: keeping database field names aligned with Swift model properties without relying on fragile parsing code. The Supabase Swift client solves this elegantly by decoding responses directly into `Codable` structs. With `CodingKeys`, snake_case database columns like `created_at` or `user_id` can be mapped cleanly to camelCase Swift properties such as `createdAt` and `userId`, keeping both the database schema and Swift code idiomatic.
The result is a safer and far more maintainable architecture. Because the models are validated at compile time, typos and mismatched property names are caught early instead of turning into runtime bugs. At the same time, the networking layer stays lightweight and expressive, with almost no boilerplate required. For teams building backend-connected iOS apps, combining Supabase with Swift’s `Codable` system and custom `CodingKeys` creates a workflow that feels modern, reliable, and surprisingly effortless.
struct Student: Identifiable, Codable {
let id: UUID
let teacherId: UUID
let studentCode: String
var displayName: String
let joinedAt: Date
let isActive: Bool
enum CodingKeys: String, CodingKey {
case id
case teacherId = "teacher_id"
case studentCode = "student_code"
case displayName = "display_name"
case joinedAt = "joined_at"
case isActive = "is_active"
}
}
// The entire fetch is type-safe – the compiler catches mismatches
let students: [Student] = try await supabaseService.client
.from("students")
.select()
.eq("teacher_id", value: teacher.id.uuidString)
.eq("is_active", value: true)
.order("joined_at", ascending: false)
.execute()
.value
