added JSONValue additions

Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
This commit is contained in:
Matt Bruce 2022-06-24 09:57:34 -05:00
parent 05a549c633
commit acf5aae880

View File

@ -13,6 +13,7 @@ public typealias JSONValueDictionary = [String: JSONValue]
public enum JSONValueError: Error {
case encode
case TypeMismatch
}
extension Optional {
@ -68,6 +69,38 @@ public enum JSONValue: Codable, Equatable {
case .null: break
}
}
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 try! object.toJSONAny()
case .array(let array): return try! array.toJSONArray()
case .null: return NSNull()
}
}
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) }
}
public func ==(lhs: JSONValue, rhs: JSONValue) -> Bool {