Skip to content

Lesson 9 of 9 · 26m

Sharing Models Between iOS and Server Without Tight Coupling

Share transport DTOs through a small Swift package, version compatibility deliberately, and keep Fluent persistence models out of client contracts.

Sharing Swift types between iOS and Vapor feels like a cheat code until the server model gains a database-only field and every client inherits the coupling. The technique is excellent when you share the correct layer: wire contracts, not persistence.

Share DTOs, not Fluent models

public struct ProjectDTO: Codable, Sendable, Equatable {
    public var id: UUID
    public var name: String
    public var createdAt: Date
    public var owner: UserSummaryDTO

    public init(id: UUID, name: String, createdAt: Date, owner: UserSummaryDTO) {
        self.id = id
        self.name = name
        self.createdAt = createdAt
        self.owner = owner
    }
}

Do not share final class Project: Model. Property wrappers, relationships, optional pre-insertion IDs, soft deletion, and mutable persistence semantics are server implementation details.

Keep the package small

APIContracts/
  Package.swift
  Sources/APIContracts/
    ProjectDTO.swift
    UserSummaryDTO.swift
    ErrorDTO.swift

Ideally depend only on Foundation. If the iOS client must compile Vapor, Fluent, NIO, and database drivers to use one struct, you have recreated the coupling problem with longer build times.

Codable is not a compatibility strategy

adding optional field       usually compatible
adding required field       breaks old clients
renaming a property         breaks wire format unless keys are pinned
changing String to UUID     breaks decoding
changing nullability        changes decoding or semantics

Use CodingKeys when the wire name must survive Swift refactors:

enum CodingKeys: String, CodingKey {
    case id
    case displayName = "display_name"
}

Agree on dates and money

Both sides need the same date strategy:

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

Do not send money as binary floating point. Use integer minor units or decimal strings with explicit currency:

{"amountMinorUnits": 1299, "currency": "USD"}

Test the wire, not just the round trip

Record canonical JSON fixtures in the shared package and test them in server and client CI. Round trips through the same encoder and decoder can hide a shared mistake. Package versions help humans reason about source compatibility; deployed compatibility is behavior. Breaking changes belong in a new endpoint version or a deliberate migration window.

Field notes

  • If a type needs server-only state, it is not a shared DTO.
  • Make initializers public; integration otherwise fails in boring ways.
  • Do not import server frameworks into the contracts package for one helper.
  • Removing a response field is breaking even if the newest app no longer reads it.

Was this lesson helpful?

Sign in to rate