SPB Git

Repository Public

Lossy.swift 7.5 KB 190 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Core/Util/Lossy.swift10// Description      : décodage JSON tolérant — les sources publient des formes11//                    variables.12// Module           : VraiPrix13// Repository       : https://git.spboucher.ai/vrai-prix-ios-v314// Project Website  : https://www.vrai-prix.com15// Created          : 2026-11-2616// Last Modified    : 2026-11-2617//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation9192/// Clé de décodage libre (dictionnaires à clés dynamiques).93struct AnyKey: CodingKey, Hashable {94    var stringValue: String95    var intValue: Int? { nil }96    init(_ s: String) { stringValue = s }97    init?(stringValue: String) { self.stringValue = stringValue }98    init?(intValue: Int) { return nil }99}100101/// Élément de tableau qui n'empêche pas le reste du tableau d'être lu.102struct Lossy<T: Decodable>: Decodable {103    let value: T?104    init(from decoder: Decoder) throws {105        value = try? T(from: decoder)106    }107}108109extension KeyedDecodingContainer {110    /// Chaîne ; un nombre est converti.111    func str(_ k: Key) -> String? {112        if let s = try? decode(String.self, forKey: k) { return s }113        if let i = try? decode(Int.self, forKey: k) { return String(i) }114        if let d = try? decode(Double.self, forKey: k) { return String(d) }115        return nil116    }117118    /// Chaîne non vide, sinon nil.119    func text(_ k: Key) -> String? {120        guard let s = str(k)?.trimmingCharacters(in: .whitespacesAndNewlines), !s.isEmpty else { return nil }121        return s122    }123124    /// Nombre ; une chaîne numérique est convertie.125    func dbl(_ k: Key) -> Double? {126        if let d = try? decode(Double.self, forKey: k) { return d.isFinite ? d : nil }127        if let s = try? decode(String.self, forKey: k) { return Double(s.replacingOccurrences(of: ",", with: ".")) }128        if let b = try? decode(Bool.self, forKey: k) { return b ? 1 : 0 }129        return nil130    }131132    func int(_ k: Key) -> Int? {133        if let i = try? decode(Int.self, forKey: k) { return i }134        if let d = dbl(k) { return Int(d.rounded()) }135        return nil136    }137138    /// Booléen ; 0/1 et « true »/« oui » sont acceptés.139    func bool(_ k: Key) -> Bool? {140        if let b = try? decode(Bool.self, forKey: k) { return b }141        if let i = try? decode(Int.self, forKey: k) { return i != 0 }142        if let d = try? decode(Double.self, forKey: k) { return d != 0 }143        if let s = try? decode(String.self, forKey: k) {144            switch s.lowercased() {145            case "true", "1", "oui", "yes": return true146            case "false", "0", "non", "no": return false147            default: return nil148            }149        }150        return nil151    }152153    func opt<T: Decodable>(_ k: Key, _ type: T.Type = T.self) -> T? {154        try? decode(T.self, forKey: k)155    }156157    /// Tableau qui saute les éléments illisibles.158    func list<T: Decodable>(_ k: Key, _ type: T.Type = T.self) -> [T] {159        ((try? decode([Lossy<T>].self, forKey: k)) ?? []).compactMap(\.value)160    }161162    /// Tableau de chaînes ; accepte aussi un tableau encodé en chaîne JSON.163    func strings(_ k: Key) -> [String] {164        if let a = try? decode([Lossy<String>].self, forKey: k) { return a.compactMap(\.value) }165        if let s = try? decode(String.self, forKey: k), let d = s.data(using: .utf8),166           let a = try? JSONDecoder().decode([Lossy<String>].self, from: d) {167            return a.compactMap(\.value)168        }169        return []170    }171172    /// Dictionnaire de booléens tolérant (valeurs 0/1 acceptées).173    func flags(_ k: Key) -> [String: Bool] {174        guard let c = try? nestedContainer(keyedBy: AnyKey.self, forKey: k) else { return [:] }175        var out: [String: Bool] = [:]176        for key in c.allKeys { if let b = c.bool(key) { out[key.stringValue] = b } }177        return out178    }179180    /// Objet imbriqué, ou le même objet encodé en chaîne JSON (cas de `digest`).181    func objectOrEncoded<T: Decodable>(_ k: Key, _ type: T.Type = T.self) -> T? {182        // la chaîne d'abord : un type au décodage tolérant accepterait la chaîne sans rien y lire183        if let s = try? decode(String.self, forKey: k) {184            guard let d = s.data(using: .utf8) else { return nil }185            return try? JSONDecoder().decode(T.self, from: d)186        }187        return try? decode(T.self, forKey: k)188    }189}190
Files main
Menu

Theme