Hi Eddie,
Normally network data model != database (core data) model. You should have a separated data model and from my experience this save you from many problems. Also any networking cache should be done with default http, let the system do it, or custom saving the response on disk.
Keeping the some model data you can do this (using Active Record):
struct Channel: Identifiable, Codable {
let id: String
let name: String
let genre: String
let logo: URL?
static func saveChannels(_ channels: [Self], on: …) async throws { … }
// Factory Methods (set the data source object or protocol)
static func all(on: …) async throws -> [Self] { … }
static func favorites(on: …) async throws -> [Self] { … }
}
Using repository / manager pattern:
struct Channel: Identifiable, Codable {
let id: String
let name: String
let genre: String
let logo: URL?
}
protocol ChannelManager {
static func loadAllChannels() async throws -> [Channel]
static func loadFavoriteChannels() async throws -> [Channel]
static func saveChannels(_ channels: [Channel]) async throws
}
struct NetworkChannelManager: ChannelManager {
static func loadAllChannels() async throws -> [Channel] { … }
static func loadFavoriteChannels() async throws -> [Channel] { … }
static func saveChannels(_ channels: [Channel]) async throws { … }
}
struct LocalChannelManager: ChannelManager {
static func loadAllChannels() async throws -> [Channel] { … }
static func loadFavoriteChannels() async throws -> [Channel] { … }
static func saveChannels(_ channels: [Channel]) async throws { … }
}
Example from Vapor platform:
Uses Active Record pattern for data access where you can set the data source.
// An example of Fluent's query API.
let planets = try await Planet.query(on: database)
.filter(\.$type == .gasGiant)
.sort(\.$name)
.with(\.$star)
.all()
// Fetches all planets.
let planets = try await Planet.query(on: database).all()
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: