Various improvements

This commit is contained in:
Ilya Laktyushin
2024-11-07 16:32:33 +01:00
parent 8ec6964dfe
commit 37c91f89c5
46 changed files with 3649 additions and 163 deletions

View File

@@ -50,6 +50,18 @@ extension JSON {
return nil
}
}
public init?(dictionary: [String: Any]) {
var values: [String: JSON] = [:]
for (key, value) in dictionary {
if let v = JSON(value) {
values[key] = v
} else {
return nil
}
}
self = .dictionary(values)
}
}
extension JSON: Collection {
@@ -125,7 +137,7 @@ extension JSON {
get {
switch self {
case .null:
return 0
return NSNull()
case let .number(value):
return value
case let .string(value):
@@ -172,6 +184,18 @@ extension JSON {
}
}
extension JSON {
public var string: String? {
guard let jsonData = try? JSONSerialization.data(withJSONObject: self.value) else {
return nil
}
guard let jsonDataString = String(data: jsonData, encoding: .utf8) else {
return nil
}
return jsonDataString
}
}
extension JSON: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, Any)...) {
self = .dictionary(elements.reduce([String: JSON]()) { (dictionary, element) in
@@ -195,6 +219,12 @@ private protocol JSONValue {
var jsonValue: JSON { get }
}
extension NSNull: JSONElement, JSONValue {
var jsonValue: JSON {
return .null
}
}
extension Int: JSONElement, JSONValue {
var jsonValue: JSON {
return .number(Double(self))