import Foundation // Nachsichtiges Lesen: ein Feld mit falschem Typ ist "unbekannt", kein Fehler. Python schreibt // Zahlen mal als int, mal als float, und manche Felder (Platz, Blinds) mal als Text, mal als Zahl. private struct Beliebig: Decodable { var text: String? var zahl: Double? init(from d: Decoder) throws { let c = try d.singleValueContainer() if let s = try? c.decode(String.self) { text = s; zahl = Double(s) } else if let b = try? c.decode(Bool.self) { text = b ? "ja" : "nein" } else if let i = try? c.decode(Int.self) { text = String(i); zahl = Double(i) } else if let x = try? c.decode(Double.self) { text = Format.roh(x); zahl = x } } } /// Ein Listeneintrag, der sich nicht lesen laesst, faellt weg statt die ganze Liste zu kippen. private struct Vielleicht: Decodable { var wert: T? init(from d: Decoder) throws { wert = try? T(from: d) } } extension KeyedDecodingContainer { func text(_ k: Key) -> String? { (try? decodeIfPresent(Beliebig.self, forKey: k))??.text } func zahl(_ k: Key) -> Double? { guard let b = (try? decodeIfPresent(Beliebig.self, forKey: k)) ?? nil else { return nil } // Ein Text ist nur dann eine Zahl, wenn Python ihn als Zahl schickte - "0.05/0.1" nicht. return b.zahl } func wahr(_ k: Key) -> Bool { ((try? decodeIfPresent(Bool.self, forKey: k)) ?? nil) ?? false } func liste(_ k: Key) -> [String] { ((try? decodeIfPresent([Vielleicht].self, forKey: k)) ?? nil)?.compactMap { $0.wert?.text } ?? [] } func objekte(_ k: Key) -> [T] { ((try? decodeIfPresent([Vielleicht].self, forKey: k)) ?? nil)?.compactMap(\.wert) ?? [] } /// Ein Objekt aus Texten (Vorgaben, Werte, Feldnamen); was kein Text ist, faellt weg. func woerter(_ k: Key) -> [String: String] { ((try? decodeIfPresent([String: Vielleicht].self, forKey: k)) ?? nil)?.compactMapValues { $0.wert?.text } ?? [:] } }