Skip to content

Commit

Permalink
♻️ (AccountKit): Professions - refactor to use static methods and con…
Browse files Browse the repository at this point in the history
…tainer
  • Loading branch information
ladislas committed Feb 7, 2024
1 parent 57863a7 commit f0137a0
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ struct MainView: View {
var body: some View {
Text("Hello, AccountKit!")
.onAppear {
let professions = Professions()
for profession in professions.list {
print("version: \(professions.version)")
let professions = Professions.list
for (index, profession) in professions.enumerated() {
print("index: \(index + 1)")
print("version: \(Professions.version)")
print("id: \(profession.id)")
print("name: \(profession.name)")
print("description: \(profession.description)")
Expand Down
47 changes: 35 additions & 12 deletions Modules/AccountKit/Sources/Models/Professions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,53 @@ import Yams

// MARK: - Professions

public struct Professions: Codable {
public class Professions: Codable {
// MARK: Lifecycle

public init() {
private init() {
self.container = Self.loadProfessions()
}

// MARK: Public

public static var list: [Profession] {
shared.container.list
}

public static var version: Version {
shared.container.version
}

public static func profession(for id: String) -> Profession? {
self.list.first(where: { $0.id == id })
}

// MARK: Private

private struct ProfessionsContainer: Codable {
let version: Version
let list: [Profession]
}

private static let shared: Professions = .init()

private let container: ProfessionsContainer

private static func loadProfessions() -> ProfessionsContainer {
if let fileURL = Bundle.module.url(forResource: "professions", withExtension: "yml") {
do {
let yamlString = try String(contentsOf: fileURL, encoding: .utf8)
self = try YAMLDecoder().decode(Professions.self, from: yamlString)
let container = try YAMLDecoder().decode(ProfessionsContainer.self, from: yamlString)
return container
} catch {
log.error("Failed to read YAML file: \(error)")
self.version = Version(major: 0, minor: 0, patch: 0)
self.list = []
return ProfessionsContainer(version: .init(1, 0, 0), list: [])
}
} else {
log.error("professions.yml not found")
self.version = Version(major: 0, minor: 0, patch: 0)
self.list = []
return ProfessionsContainer(version: .init(1, 0, 0), list: [])
}
}

// MARK: Public

public let version: Version
public let list: [Profession]
}

// MARK: - Profession
Expand Down

0 comments on commit f0137a0

Please sign in to comment.