-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHadithModels.swift
52 lines (44 loc) · 1.54 KB
/
HadithModels.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import Foundation
// MARK: - Hadith Models
struct HadithResponse: Decodable {
let hadiths: HadithsData
}
struct HadithsData: Decodable {
let data: [Hadith]
}
struct Hadith: Decodable {
let hadithNumber: Int
let hadithArabic: String
let hadithEnglish: String
// Custom decoding to handle "hadithNumber" as String or Int
enum CodingKeys: String, CodingKey {
case hadithNumber, hadithArabic, hadithEnglish
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// Try to decode hadithNumber as Int first
if let number = try? container.decode(Int.self, forKey: .hadithNumber) {
hadithNumber = number
}
// If it fails, try decoding as String and convert to Int
else {
let numberString = try container.decode(String.self, forKey: .hadithNumber)
guard let number = Int(numberString) else {
throw DecodingError.dataCorruptedError(
forKey: .hadithNumber,
in: container,
debugDescription: "hadithNumber is not a valid integer"
)
}
hadithNumber = number
}
hadithArabic = try container.decode(String.self, forKey: .hadithArabic)
hadithEnglish = try container.decode(String.self, forKey: .hadithEnglish)
}
}
// Extension to help with String to Int conversion if needed
extension String {
var asInt: Int? {
return Int(self)
}
}