SPB Git

Repository Public

Lossy.swift 4.1 KB 110 lines swift

1//2//  Fabri-Ka iOS v23//  File: FabriKa/Core/Util/Lossy.swift4//  Description: décodage JSON tolérant — les sources publient des formes variables.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import Foundation1112/// Clé de décodage libre (dictionnaires à clés dynamiques).13struct AnyKey: CodingKey, Hashable {14    var stringValue: String15    var intValue: Int? { nil }16    init(_ s: String) { stringValue = s }17    init?(stringValue: String) { self.stringValue = stringValue }18    init?(intValue: Int) { return nil }19}2021/// Élément de tableau qui n'empêche pas le reste du tableau d'être lu.22struct Lossy<T: Decodable>: Decodable {23    let value: T?24    init(from decoder: Decoder) throws {25        value = try? T(from: decoder)26    }27}2829extension KeyedDecodingContainer {30    /// Chaîne ; un nombre est converti.31    func str(_ k: Key) -> String? {32        if let s = try? decode(String.self, forKey: k) { return s }33        if let i = try? decode(Int.self, forKey: k) { return String(i) }34        if let d = try? decode(Double.self, forKey: k) { return String(d) }35        return nil36    }3738    /// Chaîne non vide, sinon nil.39    func text(_ k: Key) -> String? {40        guard let s = str(k)?.trimmingCharacters(in: .whitespacesAndNewlines), !s.isEmpty else { return nil }41        return s42    }4344    /// Nombre ; une chaîne numérique est convertie.45    func dbl(_ k: Key) -> Double? {46        if let d = try? decode(Double.self, forKey: k) { return d.isFinite ? d : nil }47        if let s = try? decode(String.self, forKey: k) { return Double(s.replacingOccurrences(of: ",", with: ".")) }48        if let b = try? decode(Bool.self, forKey: k) { return b ? 1 : 0 }49        return nil50    }5152    func int(_ k: Key) -> Int? {53        if let i = try? decode(Int.self, forKey: k) { return i }54        if let d = dbl(k) { return Int(d.rounded()) }55        return nil56    }5758    /// Booléen ; 0/1 et « true »/« oui » sont acceptés.59    func bool(_ k: Key) -> Bool? {60        if let b = try? decode(Bool.self, forKey: k) { return b }61        if let i = try? decode(Int.self, forKey: k) { return i != 0 }62        if let d = try? decode(Double.self, forKey: k) { return d != 0 }63        if let s = try? decode(String.self, forKey: k) {64            switch s.lowercased() {65            case "true", "1", "oui", "yes": return true66            case "false", "0", "non", "no": return false67            default: return nil68            }69        }70        return nil71    }7273    func opt<T: Decodable>(_ k: Key, _ type: T.Type = T.self) -> T? {74        try? decode(T.self, forKey: k)75    }7677    /// Tableau qui saute les éléments illisibles.78    func list<T: Decodable>(_ k: Key, _ type: T.Type = T.self) -> [T] {79        ((try? decode([Lossy<T>].self, forKey: k)) ?? []).compactMap(\.value)80    }8182    /// Tableau de chaînes ; accepte aussi un tableau encodé en chaîne JSON.83    func strings(_ k: Key) -> [String] {84        if let a = try? decode([Lossy<String>].self, forKey: k) { return a.compactMap(\.value) }85        if let s = try? decode(String.self, forKey: k), let d = s.data(using: .utf8),86           let a = try? JSONDecoder().decode([Lossy<String>].self, from: d) {87            return a.compactMap(\.value)88        }89        return []90    }9192    /// Dictionnaire de booléens tolérant (valeurs 0/1 acceptées).93    func flags(_ k: Key) -> [String: Bool] {94        guard let c = try? nestedContainer(keyedBy: AnyKey.self, forKey: k) else { return [:] }95        var out: [String: Bool] = [:]96        for key in c.allKeys { if let b = c.bool(key) { out[key.stringValue] = b } }97        return out98    }99100    /// Objet imbriqué, ou le même objet encodé en chaîne JSON (cas de `digest`).101    func objectOrEncoded<T: Decodable>(_ k: Key, _ type: T.Type = T.self) -> T? {102        // la chaîne d'abord : un type au décodage tolérant accepterait la chaîne sans rien y lire103        if let s = try? decode(String.self, forKey: k) {104            guard let d = s.data(using: .utf8) else { return nil }105            return try? JSONDecoder().decode(T.self, from: d)106        }107        return try? decode(T.self, forKey: k)108    }109}110
Files main
Menu

Theme