refactored to new throws JSONAny

Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
This commit is contained in:
Matt Bruce 2022-02-15 11:00:34 -06:00
parent 5f3daa573f
commit 07cf145686

View File

@ -13,6 +13,7 @@ public typealias JSONValueDictionary = [String: JSONValue]
public enum JSONValueError: Error {
case encode
case TypeMismatch
}
extension Optional {
@ -69,25 +70,36 @@ public enum JSONValue: Codable, Equatable {
}
}
public var base: Any? {
public var base: Any {
switch self {
case .string(let string): return string
case .int(let int): return int
case .double(let double): return double
case .bool(let bool): return bool
case .object(let object): return object.toJSONAny()
case .array(let array): return ["array": array].toJSONAny()?["array"]
case .null: return nil
case .object(let object): return try! object.toJSONAny()
case .array(let array): return try! ["array": array].toJSONAny()["array"]!
case .null: return NSNull()
}
}
public func value<T>() -> T? { self.base as? T }
public func toString() -> String? { self.base as? String }
public func toDouble() -> Double? { self.base as? Double }
public func toInt() -> Int? { self.base as? Int }
public func toBool() -> Bool? { self.base as? Bool }
public func toArray<T>(of type: T.Type) -> [T]?{ self.base as? [T] }
public func toObject<T>(of type: T.Type) -> T? { self.base as? T }
public func value<T>() throws -> T {
guard let base = self.base as? T else {
throw JSONValueError.TypeMismatch
}
return base
}
private func value<T>(type: T.Type) throws -> T {
let base: T = try value()
return base
}
public func toString() throws -> String { try value(type: String.self) }
public func toDouble() throws -> Double { try value(type: Double.self) }
public func toInt() throws -> Int { try value(type: Int.self) }
public func toBool() throws -> Bool { try value(type: Bool.self) }
public func toArray<T>(of type: T.Type) throws -> [T]{ try value(type: [T].self) }
public func toObject<T>(of type: T.Type) throws -> T { try value(type: T.self) }
}