Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
struct Context: Codable {
let duration: TimeInterval
let view: String
}
struct SearchInfo: Codable {
let query: String
let numberOfMatches: Int
let context: Context
}
let searchInfos = [SearchInfo(query: "query1", numberOfMatches: 1, context: Context(duration: 1.0, view: "view1")),
SearchInfo(query: "query2", numberOfMatches: 2, context: Context(duration: 2.0, view: "view2"))]
// Converting to dictionary
extension SearchInfo {
var dictionaryRepresentation: [String: Any] {
let data = try! JSONEncoder().encode(self)
return try! JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
}
}
// Converting back to struct
extension SearchInfo {
init?(dictionary: [String: Any]) {
guard let data = try? JSONSerialization.data(withJSONObject: dictionary, options: []) else { return nil }
guard let info = try? JSONDecoder().decode(SearchInfo.self, from: data) else { return nil }
self = info
}
}
let defaults = UserDefaults()
// [Struct] -> [Dictionary]
let searchInfoDictionaries = searchInfos.map({ $0.dictionaryRepresentation })
// [Dictionary] to UserDefaults
defaults.set(searchInfoDictionaries, forKey: "Searches")
// [Dictionary] from UserDefaults
let dictionariesFromUserDefaults = defaults.array(forKey: "Searches")! as! [[String: Any]]
// [Dictionary] -> [Struct]
let convertedSearchInfos = dictionariesFromUserDefaults.compactMap({ SearchInfo(dictionary: $0) })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.