Skip to content

Instantly share code, notes, and snippets.

@perseusrealdeal
Last active March 3, 2024 11:54
Show Gist options
  • Save perseusrealdeal/918c25633122e64d51f363f00059f6f8 to your computer and use it in GitHub Desktop.
Save perseusrealdeal/918c25633122e64d51f363f00059f6f8 to your computer and use it in GitHub Desktop.
Json Data to [String: Any]. Give it a path by closure.
//
// JsonDataDictionaryGift.swift
// Gifts
//
// Just a gift. Tested with Swift 4.2 compiler.
// https://gist.github.com/perseusrealdeal/918c25633122e64d51f363f00059f6f8
//
/* Perseus Logger source code */
/* https://gist.github.com/perseusrealdeal/df456a9825fcface44eca738056eb6d5 */
import Foundation
public class DataDictionarySource {
// MARK: - Internals
private var json: (() -> Data)?
// MARK: - Contract
public var path: (() -> Data)? {
didSet {
json = path
}
}
public var data: [String: Any]? {
guard let source = json else { return nil }
let dataSource = source()
let opts: JSONSerialization.ReadingOptions = [.mutableContainers]
do {
let object = try JSONSerialization.jsonObject(with: dataSource, options: opts)
guard
let json = object as? [String: Any]
else {
// log.message("[\(type(of: self))].\(#function), Dictionary.", .error)
return nil
}
return json
} catch {
// log.message("[\(type(of: self))].\(#function) \(error)", .error)
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment