Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Lou-Ka iOS9// File : LouKa/Core/Models/Listing.swift10// Description : annonce de logement (liste et fiche) — décodage tolérant.11// Module : LouKa12// Repository : https://git.spboucher.ai/lou-ka-ios-v313// Project Website : https://www.lou-ka.com14// Created : 2026-11-2515// Last Modified : 2026-11-2816//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : None specified (no license file in this repository)82// Maintainer : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import CoreLocation90import Foundation9192/// Verdict de prix : position du loyer affiché par rapport à l'intervalle du loyer de marché estimé.93/// Absent quand l'incertitude est trop grande : aucun verdict n'est alors affiché.94enum Verdict: String, Codable, Sendable, CaseIterable {95 case sous, marche, sur9697 /// Code compact des points de carte (« s », « m », « o »).98 init?(code: String?) {99 switch code {100 case "s": self = .sous101 case "m": self = .marche102 case "o": self = .sur103 default: return nil104 }105 }106107 var label: String {108 switch self {109 case .sous: "Sous la fourchette"110 case .marche: "Dans la fourchette"111 case .sur: "Au-dessus"112 }113 }114115 var longLabel: String {116 switch self {117 case .sous: "Loyer sous la fourchette estimée"118 case .marche: "Loyer dans la fourchette estimée"119 case .sur: "Loyer au-dessus de la fourchette estimée"120 }121 }122}123124struct Parking: Sendable, Hashable {125 var available: Bool126 var included: Bool?127 var price: Double?128 var type: String?129}130131struct ListingDetails: Decodable, Sendable, Hashable {132 var inclusions: [String: Bool] = [:]133 var appliances: [String: Bool] = [:]134 var parking: Parking?135 var phone: String?136 var email: String?137 var ac: Bool?138 var elevator: Bool?139 var balcony: Bool?140 var pool: Bool?141 var gym: Bool?142 var laundry: Bool?143 var storage: Bool?144 var smoking: Bool?145 var floor: Int?146 var priceFrom: Bool = false147148 init() {}149150 init(from decoder: Decoder) throws {151 guard let c = try? decoder.container(keyedBy: AnyKey.self) else { return }152 inclusions = c.flags(AnyKey("inclusions"))153 appliances = c.flags(AnyKey("appliances"))154 // stationnement : objet détaillé, nombre de places ou simple booléen selon la source155 let pk = AnyKey("parking")156 if let p = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: pk) {157 parking = Parking(available: p.bool(AnyKey("available")) ?? true,158 included: p.bool(AnyKey("included")),159 price: p.dbl(AnyKey("price")),160 type: p.text(AnyKey("type")))161 } else if let b = c.bool(pk) {162 parking = b ? Parking(available: true) : nil163 }164 if let ct = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("contact")) {165 phone = ct.text(AnyKey("phone"))166 email = ct.text(AnyKey("email"))167 }168 ac = c.bool(AnyKey("ac"))169 elevator = c.bool(AnyKey("elevator"))170 balcony = c.bool(AnyKey("balcony"))171 pool = c.bool(AnyKey("pool"))172 gym = c.bool(AnyKey("gym"))173 laundry = c.bool(AnyKey("laundry"))174 storage = c.bool(AnyKey("storage"))175 smoking = c.bool(AnyKey("smoking"))176 floor = c.int(AnyKey("floor"))177 priceFrom = c.bool(AnyKey("price_from")) ?? false178 }179}180181struct Poi: Decodable, Sendable, Hashable, Identifiable {182 var cat: String183 var name: String184 var distM: Double185 var lat: Double?186 var lng: Double?187 var id: String { "\(cat)|\(name)|\(Int(distM))" }188189 init(from decoder: Decoder) throws {190 let c = try decoder.container(keyedBy: AnyKey.self)191 cat = c.str(AnyKey("cat")) ?? ""192 name = c.str(AnyKey("name")) ?? ""193 distM = c.dbl(AnyKey("dist_m")) ?? 0194 lat = c.dbl(AnyKey("lat"))195 lng = c.dbl(AnyKey("lng"))196 }197}198199struct Digest: Decodable, Sendable, Hashable {200 struct Section: Decodable, Sendable, Hashable {201 var titre: String202 var texte: String203 init(from decoder: Decoder) throws {204 let c = try decoder.container(keyedBy: AnyKey.self)205 titre = c.str(AnyKey("titre")) ?? ""206 texte = c.str(AnyKey("texte")) ?? ""207 }208 }209 var texteNettoye: String?210 var enBref: String?211 var sections: [Section] = []212 var bailMinMois: Int?213 var occupants: Int?214 var salleDeBain: String?215 var cuisine: String?216 var electromenagers: [String] = []217 var inclusions: [String] = []218 var contraintes: [String] = []219 var depot: String?220 var incoherences: [String] = []221222 init(from decoder: Decoder) throws {223 let c = try decoder.container(keyedBy: AnyKey.self)224 texteNettoye = c.text(AnyKey("texte_nettoye"))225 enBref = c.text(AnyKey("en_bref"))226 sections = c.list(AnyKey("sections"))227 incoherences = c.strings(AnyKey("incoherences"))228 if let f = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("faits")) {229 bailMinMois = f.int(AnyKey("duree_bail_minimale_mois"))230 occupants = f.int(AnyKey("nb_occupants_total"))231 salleDeBain = f.text(AnyKey("salle_de_bain"))232 cuisine = f.text(AnyKey("cuisine"))233 electromenagers = f.strings(AnyKey("electromenagers"))234 inclusions = f.strings(AnyKey("inclusions"))235 contraintes = f.strings(AnyKey("contraintes"))236 depot = f.text(AnyKey("depot_mentionne"))237 }238 }239}240241/// Scores de quartier (0-100) avec leurs détails.242struct ScoreSet: Sendable, Hashable {243 var walk: Double?244 var transit: Double?245 var bike: Double?246 var calme: Double?247 var services: Double?248 var global: Double?249250 static let defaultWeights: [String: Double] = ["walk": 0.30, "transit": 0.20, "bike": 0.15, "calme": 0.20, "services": 0.15]251252 func value(_ key: String) -> Double? {253 switch key {254 case "walk": walk255 case "transit": transit256 case "bike": bike257 case "calme": calme258 case "services": services259 default: nil260 }261 }262263 /// Score global recalculé avec des pondérations personnelles.264 func weighted(_ weights: [String: Double]) -> Double? {265 var total = 0.0, got = 0.0266 for (k, w) in weights { if let v = value(k) { total += w; got += w * v } }267 return total < 0.5 ? nil : (got / total * 10).rounded() / 10268 }269270 var isEmpty: Bool { walk == nil && transit == nil && bike == nil && calme == nil && services == nil && global == nil }271272 static func label(_ s: Double?) -> String? {273 guard let s else { return nil }274 if s >= 85 { return "Exceptionnel" }275 if s >= 70 { return "Excellent" }276 if s >= 55 { return "Très bon" }277 if s >= 40 { return "Moyen" }278 return "Faible"279 }280}281282struct PricePoint: Decodable, Sendable, Hashable {283 var ts: Double284 var price: Double?285 init(from decoder: Decoder) throws {286 let c = try decoder.container(keyedBy: AnyKey.self)287 ts = c.dbl(AnyKey("ts")) ?? 0288 price = c.dbl(AnyKey("price"))289 }290}291292struct Listing: Decodable, Sendable, Identifiable, Hashable {293 var uid: String294 var source: String295 var url: String?296 var title: String297 var address: String298 var sector: String299 var city: String300 var unitType: String301 var price: Double?302 var priceLabel: String?303 var availabilityDate: String?304 var areaSqft: Double?305 var pets: String?306 var furnished: Bool?307 var description: String308 var amenities: [String]309 var images: [String]310 var lat: Double?311 var lng: Double?312 var bedrooms: Double?313 var bathrooms: Double?314 var firstSeen: Double?315 var lastSeen: Double?316 var updatedAt: Double?317 var active: Bool318 var details: ListingDetails319 var dupSources: [String]320 var buildingKey: String?321 // juste valeur322 var fv: Double?323 var fvLow: Double?324 var fvHigh: Double?325 var fvDeviation: Double?326 var fvVerdict: Verdict?327 var fvConfidence: String?328 // scores de quartier (liste) ; détail complet dans `scoreDetails` (fiche)329 var scores: ScoreSet330 // fiche seulement331 var poi: [Poi]332 var digest: Digest?333 var priceHistory: [PricePoint]334 var quartier: Quartier?335 var immeuble: Immeuble?336 var hiver: Hiver?337 var scoreDetails: ScoreDetails?338 // API v3 : grandeur en nombre de pièces, attributs à trois états (clé absente = inconnu), suivi de prix339 var rooms: Int?340 var kind: String?341 var features: [String: Bool]342 var pricePrev: Double?343 /// Variation du dernier changement de prix, en fraction (−0,05 = −5 %).344 var priceDelta: Double?345 var priceChangedAt: Double?346 var priceFrom: Bool347 var imageCount: Int?348 var yearBuilt: Int?349350 var id: String { uid }351352 /// Fiche complète : les blocs riches de la route v2 (à proximité, scores détaillés, immeuble, hiver,353 /// historique) complétés par les valeurs de l'API v3, qui font foi pour l'estimation, la grandeur,354 /// les attributs et le suivi de prix.355 func merging(v3: Listing) -> Listing {356 var l = self357 l.fv = v3.fv; l.fvLow = v3.fvLow; l.fvHigh = v3.fvHigh358 l.fvDeviation = v3.fvDeviation; l.fvVerdict = v3.fvVerdict; l.fvConfidence = v3.fvConfidence359 l.rooms = v3.rooms; l.kind = v3.kind; l.features = v3.features360 l.pricePrev = v3.pricePrev; l.priceDelta = v3.priceDelta; l.priceChangedAt = v3.priceChangedAt361 l.priceFrom = v3.priceFrom; l.imageCount = v3.imageCount; l.yearBuilt = v3.yearBuilt362 l.price = v3.price ?? l.price363 l.lastSeen = v3.lastSeen ?? l.lastSeen364 if l.images.isEmpty { l.images = v3.images }365 if l.availabilityDate == nil { l.availabilityDate = v3.availabilityDate }366 if !v3.scores.isEmpty, l.scores.isEmpty { l.scores = v3.scores }367 return l368 }369370 /// Baisse de prix plausible (entre 1 % et 40 %), comme sur le site : au-delà, c'est une coquille de la source.371 var plausibleDrop: Double? {372 guard let d = priceDelta, d <= -0.01, d >= -0.4, pricePrev != nil else { return nil }373 return d374 }375376 /// Vue pour la première fois depuis moins de `days` jours.377 func isNew(days: Double = 3) -> Bool {378 guard let f = firstSeen else { return false }379 return Date().timeIntervalSince1970 - f < days * 86400380 }381382 /// Adresse publique de la fiche (partage, liens universels, Spotlight).383 var publicURL: URL? {384 var allowed = CharacterSet.urlPathAllowed; allowed.remove(charactersIn: "/?#")385 return URL(string: "https://www.lou-ka.com/logement/" + (uid.addingPercentEncoding(withAllowedCharacters: allowed) ?? uid))386 }387388 static func == (a: Listing, b: Listing) -> Bool { a.uid == b.uid && a.updatedAt == b.updatedAt && a.price == b.price }389 func hash(into hasher: inout Hasher) { hasher.combine(uid) }390391 /// Loyer plausible (mêmes bornes que le serveur) : écarte les 0 $ et les coquilles.392 static func priceIsPlausible(_ p: Double?) -> Bool {393 guard let p else { return false }394 return p >= 195 && p <= 15000395 }396397 var plausiblePrice: Double? { Listing.priceIsPlausible(price) ? price : nil }398399 var coordinate: CLLocationCoordinate2D? {400 guard let lat, let lng, abs(lat) <= 90, abs(lng) <= 180, !(lat == 0 && lng == 0) else { return nil }401 return CLLocationCoordinate2D(latitude: lat, longitude: lng)402 }403404 var displayTitle: String {405 if !title.isEmpty { return title }406 if !address.isEmpty { return address }407 return "Logement à louer"408 }409410 var cleanCity: String { Fmt.cleanCity(city) }411412 /// « Quartier · Ville »413 var place: String {414 var parts: [String] = []415 if !sector.isEmpty, sector != city { parts.append(Fmt.cleanCity(sector)) }416 if !cleanCity.isEmpty { parts.append(cleanCity) }417 return parts.isEmpty ? address : parts.joined(separator: " · ")418 }419420 var petsAllowed: Bool { pets == "oui" || pets == "conditions" }421422 var pricePerSqft: Double? {423 guard let p = plausiblePrice, let a = areaSqft, a > 100 else { return nil }424 return p / a425 }426427 init(from decoder: Decoder) throws {428 let c = try decoder.container(keyedBy: AnyKey.self)429 guard let u = c.text(AnyKey("uid")) else {430 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "annonce sans uid"))431 }432 uid = u433 source = c.str(AnyKey("source")) ?? ""434 url = c.text(AnyKey("url"))435 title = c.text(AnyKey("title")) ?? ""436 address = c.text(AnyKey("address")) ?? ""437 sector = c.text(AnyKey("sector")) ?? ""438 city = c.text(AnyKey("city")) ?? ""439 unitType = c.text(AnyKey("unit_type")) ?? ""440 price = c.dbl(AnyKey("price"))441 priceLabel = c.text(AnyKey("price_label"))442 availabilityDate = c.text(AnyKey("availability_date")) ?? c.text(AnyKey("avail"))443 areaSqft = c.dbl(AnyKey("area_sqft"))444 pets = c.text(AnyKey("pets"))445 furnished = c.bool(AnyKey("furnished"))446 rooms = c.int(AnyKey("rooms"))447 kind = c.text(AnyKey("kind"))448 features = c.flags(AnyKey("features"))449 pricePrev = c.dbl(AnyKey("price_prev"))450 priceDelta = c.dbl(AnyKey("price_delta"))451 priceChangedAt = c.dbl(AnyKey("price_changed_at"))452 imageCount = c.int(AnyKey("n_images"))453 yearBuilt = c.int(AnyKey("year_built"))454 description = c.text(AnyKey("description")) ?? ""455 amenities = c.strings(AnyKey("amenities"))456 images = c.strings(AnyKey("images")).filter { $0.hasPrefix("http") }457 // listes de l'API v3 : une seule photo (`image`) et le nombre total (`n_images`)458 if images.isEmpty, let one = c.text(AnyKey("image")), one.hasPrefix("http") { images = [one] }459 lat = c.dbl(AnyKey("lat"))460 lng = c.dbl(AnyKey("lng"))461 bedrooms = c.dbl(AnyKey("bedrooms"))462 bathrooms = c.dbl(AnyKey("bathrooms"))463 firstSeen = c.dbl(AnyKey("first_seen"))464 lastSeen = c.dbl(AnyKey("last_seen"))465 updatedAt = c.dbl(AnyKey("updated_at"))466 active = c.bool(AnyKey("active")) ?? true467 details = c.objectOrEncoded(AnyKey("details")) ?? ListingDetails()468 dupSources = c.strings(AnyKey("dup_sources"))469 buildingKey = c.text(AnyKey("building_key"))470 fv = c.dbl(AnyKey("fv"))471 fvLow = c.dbl(AnyKey("fv_low"))472 fvHigh = c.dbl(AnyKey("fv_high"))473 // v2 : fraction (`fv_deviation`) ; v3 : pour cent (`fv_dev`). Gardé en fraction.474 fvDeviation = c.dbl(AnyKey("fv_deviation")) ?? c.dbl(AnyKey("fv_dev")).map { $0 / 100 }475 fvVerdict = c.text(AnyKey("fv_verdict")).flatMap(Verdict.init(rawValue:))476 fvConfidence = c.text(AnyKey("fv_confidence")) ?? c.text(AnyKey("fv_conf"))477 scores = ScoreSet(walk: c.dbl(AnyKey("ks_walk")), transit: c.dbl(AnyKey("ks_transit")),478 bike: c.dbl(AnyKey("ks_bike")), calme: c.dbl(AnyKey("ks_calme")),479 services: c.dbl(AnyKey("ks_services")), global: c.dbl(AnyKey("ks_global")))480 poi = c.list(AnyKey("poi"))481 digest = c.objectOrEncoded(AnyKey("digest"))482 priceHistory = c.list(AnyKey("price_history"))483 quartier = c.opt(AnyKey("quartier"))484 immeuble = c.opt(AnyKey("immeuble"))485 hiver = c.opt(AnyKey("hiver"))486 scoreDetails = c.opt(AnyKey("kascores"))487 if let d = scoreDetails, scores.isEmpty { scores = d.set }488 priceFrom = c.bool(AnyKey("price_from")) ?? details.priceFrom489 }490}491492// MARK: - Blocs de la fiche493494struct ScoreDetails: Decodable, Sendable, Hashable {495 struct WalkCat: Decodable, Sendable, Hashable {496 var cat: String497 var distM: Double?498 var pts: Double499 init(from decoder: Decoder) throws {500 let c = try decoder.container(keyedBy: AnyKey.self)501 cat = c.str(AnyKey("cat")) ?? ""502 distM = c.dbl(AnyKey("dist_m"))503 pts = c.dbl(AnyKey("pts")) ?? 0504 }505 }506 struct Noise: Decodable, Sendable, Hashable {507 var source: String508 var distM: Double?509 init(from decoder: Decoder) throws {510 let c = try decoder.container(keyedBy: AnyKey.self)511 source = c.str(AnyKey("source")) ?? ""512 distM = c.dbl(AnyKey("dist_m"))513 }514 }515 var set: ScoreSet516 var walkCats: [WalkCat] = []517 var busStopM: Double?518 var metroM: Double?519 var bikeKm: Double?520 var noise: [Noise] = []521 var version: String?522523 init(from decoder: Decoder) throws {524 let c = try decoder.container(keyedBy: AnyKey.self)525 set = ScoreSet(walk: c.dbl(AnyKey("walk")), transit: c.dbl(AnyKey("transit")), bike: c.dbl(AnyKey("bike")),526 calme: c.dbl(AnyKey("calme")), services: c.dbl(AnyKey("services")), global: c.dbl(AnyKey("global")))527 version = c.text(AnyKey("version"))528 guard let d = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("details")) else { return }529 if let w = try? d.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("walk")) { walkCats = w.list(AnyKey("cats")) }530 if let t = try? d.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("transit")) {531 busStopM = t.dbl(AnyKey("arret_bus_m"))532 metroM = t.dbl(AnyKey("station_metro_m"))533 }534 if let b = try? d.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("bike")) { bikeKm = b.dbl(AnyKey("km_cyclables_1km")) }535 if let q = try? d.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("calme")) { noise = q.list(AnyKey("sources_bruit")) }536 }537}538539struct Quartier: Decodable, Sendable, Hashable {540 var population: Double?541 var ageMedian: Double?542 var revenuMedian: Double?543 var pctLocataires: Double?544 var loyerMoyen: Double?545 var pctFrancais: Double?546 var pctUniv: Double?547 var chaleurClasse: Int?548 var crimeTexte: String?549550 init(from decoder: Decoder) throws {551 let c = try decoder.container(keyedBy: AnyKey.self)552 if let d = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("demographie")) {553 population = d.dbl(AnyKey("population"))554 ageMedian = d.dbl(AnyKey("age_median"))555 revenuMedian = d.dbl(AnyKey("revenu_median"))556 pctLocataires = d.dbl(AnyKey("pct_locataires"))557 loyerMoyen = d.dbl(AnyKey("loyer_moyen"))558 pctFrancais = d.dbl(AnyKey("pct_francais"))559 pctUniv = d.dbl(AnyKey("pct_univ"))560 }561 if let h = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("chaleur")) { chaleurClasse = h.int(AnyKey("classe")) }562 if let k = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("crime")) {563 if k.str(AnyKey("type")) == "points", let n = k.int(AnyKey("douze_mois")) {564 let prev = k.int(AnyKey("douze_mois_precedents"))565 let r = k.int(AnyKey("rayon_m")) ?? 500566 crimeTexte = "\(Fmt.int(n)) événements rapportés à moins de \(r) m sur 12 mois" + (prev.map { " (\(Fmt.int($0)) l'année précédente)" } ?? "")567 } else if let i = k.dbl(AnyKey("indice")) {568 let ca = k.dbl(AnyKey("indice_canada"))569 crimeTexte = "Indice de gravité de la criminalité : \(Fmt.int(i))" + (ca.map { " (Canada : \(Fmt.int($0)))" } ?? "")570 }571 }572 }573574 var hasDemographics: Bool { population != nil || ageMedian != nil || revenuMedian != nil || pctLocataires != nil }575}576577struct Immeuble: Decodable, Sendable, Hashable {578 struct Unit: Decodable, Sendable, Hashable, Identifiable {579 var uid: String580 var unitType: String?581 var price: Double?582 var id: String { uid }583 init(from decoder: Decoder) throws {584 let c = try decoder.container(keyedBy: AnyKey.self)585 uid = c.str(AnyKey("uid")) ?? UUID().uuidString586 unitType = c.text(AnyKey("unit_type"))587 price = c.dbl(AnyKey("price"))588 }589 }590 var annoncesTotal: Int?591 var annoncesActives: Int?592 var annonces12m: Int?593 var unitesEstimees: Int?594 var loyerMedian: Double?595 var variation12m: Double?596 var rotationClasse: String?597 var gestionnaires: [String] = []598 var premiereObservation: Double?599 var unitesActives: [Unit] = []600601 init(from decoder: Decoder) throws {602 let c = try decoder.container(keyedBy: AnyKey.self)603 annoncesTotal = c.int(AnyKey("annonces_total"))604 annoncesActives = c.int(AnyKey("annonces_actives"))605 annonces12m = c.int(AnyKey("annonces_12m"))606 unitesEstimees = c.int(AnyKey("unites_estimees"))607 loyerMedian = c.dbl(AnyKey("loyer_median"))608 gestionnaires = c.strings(AnyKey("gestionnaires"))609 premiereObservation = c.dbl(AnyKey("premiere_observation"))610 unitesActives = c.list(AnyKey("unites_actives"))611 if let p = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("pression_loyers")) { variation12m = p.dbl(AnyKey("variation_12m")) }612 if let r = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("rotation")) { rotationClasse = r.text(AnyKey("classe")) }613 }614}615616struct Hiver: Decodable, Sendable, Hashable {617 struct Item: Decodable, Sendable, Hashable, Identifiable {618 var critere: String619 var score: Double620 var distanceM: Double?621 var nom: String?622 var id: String { critere }623 init(from decoder: Decoder) throws {624 let c = try decoder.container(keyedBy: AnyKey.self)625 critere = c.str(AnyKey("critere")) ?? ""626 score = c.dbl(AnyKey("score")) ?? 0627 distanceM = c.dbl(AnyKey("distance_m"))628 nom = c.text(AnyKey("nom"))629 }630 }631 var score: Double632 var classe: String?633 var detail: [Item]634 init(from decoder: Decoder) throws {635 let c = try decoder.container(keyedBy: AnyKey.self)636 guard let s = c.dbl(AnyKey("score")) else {637 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "hiver sans score"))638 }639 score = s640 classe = c.text(AnyKey("classe"))641 detail = c.list(AnyKey("detail"))642 }643}644