SHARE
TWEET

Untitled

a guest May 22nd, 2019 94 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. struct Context: Codable {
  2.     let duration: TimeInterval
  3.     let view: String
  4. }
  5.  
  6. struct SearchInfo: Codable {
  7.     let query: String
  8.     let numberOfMatches: Int
  9.     let context: Context
  10. }
  11.  
  12. let searchInfos = [SearchInfo(query: "query1", numberOfMatches: 1, context: Context(duration: 1.0, view: "view1")),
  13.                    SearchInfo(query: "query2", numberOfMatches: 2, context: Context(duration: 2.0, view: "view2"))]
  14.  
  15. // Converting to dictionary
  16. extension SearchInfo {
  17.     var dictionaryRepresentation: [String: Any] {
  18.         let data = try! JSONEncoder().encode(self)
  19.         return try! JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
  20.     }
  21. }
  22.  
  23. // Converting back to struct
  24. extension SearchInfo {
  25.     init?(dictionary: [String: Any]) {
  26.         guard let data = try? JSONSerialization.data(withJSONObject: dictionary, options: []) else { return nil }
  27.         guard let info = try? JSONDecoder().decode(SearchInfo.self, from: data) else { return nil }
  28.         self = info
  29.     }
  30. }
  31.  
  32. let defaults = UserDefaults()
  33.  
  34. // [Struct] -> [Dictionary]
  35. let searchInfoDictionaries = searchInfos.map({ $0.dictionaryRepresentation })
  36.  
  37. // [Dictionary] to UserDefaults
  38. defaults.set(searchInfoDictionaries, forKey: "Searches")
  39.  
  40. // [Dictionary] from UserDefaults
  41. let dictionariesFromUserDefaults = defaults.array(forKey: "Searches")! as! [[String: Any]]
  42.  
  43. // [Dictionary] -> [Struct]
  44. let convertedSearchInfos = dictionariesFromUserDefaults.compactMap({ SearchInfo(dictionary: $0) })
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top