-
Notifications
You must be signed in to change notification settings - Fork 512
Expand file tree
/
Copy pathKeyedDecodingContainer+ParsingOptions.swift
More file actions
45 lines (40 loc) · 1.64 KB
/
KeyedDecodingContainer+ParsingOptions.swift
File metadata and controls
45 lines (40 loc) · 1.64 KB
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
//
// KeyedDecodingContainer+ParsingOptions.swift
// OpenAI
//
// Created by Oleksii Nezhyborets on 27.03.2025.
//
import Foundation
extension KeyedDecodingContainer {
func decodeString(forKey key: KeyedDecodingContainer<K>.Key, parsingOptions: ParsingOptions) throws -> String {
try self.decode(String.self, forKey: key, parsingOptions: parsingOptions, defaultValue: "")
}
func decodeTimeInterval(forKey key: KeyedDecodingContainer<K>.Key, parsingOptions: ParsingOptions) throws -> TimeInterval {
try self.decode(TimeInterval.self, forKey: key, parsingOptions: parsingOptions, defaultValue: 0)
}
func decodeInt(forKey key: KeyedDecodingContainer<K>.Key, parsingOptions: ParsingOptions) throws -> Int {
try self.decode(Int.self, forKey: key, parsingOptions: parsingOptions, defaultValue: 0)
}
func decode<T: Decodable>(_ type: T.Type, forKey key: KeyedDecodingContainer<K>.Key, parsingOptions: ParsingOptions, defaultValue: T) throws -> T {
do {
return try decode(T.self, forKey: key)
} catch {
switch error {
case DecodingError.keyNotFound:
if parsingOptions.contains(.fillRequiredFieldIfKeyNotFound) {
return defaultValue
} else {
throw error
}
case DecodingError.valueNotFound:
if parsingOptions.contains(.fillRequiredFieldIfValueNotFound) {
return defaultValue
} else {
throw error
}
default:
throw error
}
}
}
}