在我的项目中,我有一组字典:
var list = [[String: Any]] ()
简单来说,我所做的就是从 URL 下载 JSON 文件
// json parsing 2
let url:String = "https://jsonplaceholder.typicode.com/users"
let urlRequest = URL(string: url)
URLSession.shared.dataTask(with: urlRequest!, completionHandler: {(data, response, error) in
if(error != nil)
{
print(error.debugDescription)
}else{
do {
self.list = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
as! [[String: Any]]
OperationQueue.main.addOperation {
self.tableView.reloadData()
}
}catch let error as NSError{
print(error)
}
}
}).resume()
现在,在列表(这是一个字典数组)中,我拥有了我感兴趣的所有数据。但是如果我想挑选一个值,或者打印 list 的整个内容,我该怎么办?
EDIT: also, I can simplify the structure and do not use an array of dictionaries, but something simpler?
最佳答案
或者你可以使用归档
import Foundation
class UserDataManager {
var documentsURL: NSURL?
var fileURL:NSURL?
func setFileURL(file: String) {
documentsURL = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask)[0] as NSURL?
fileURL = documentsURL!.appendingPathComponent(file) as NSURL?
}
func write(file: String, mDict: NSDictionary) {
setFileURL(file: file)
let data : NSData = NSKeyedArchiver.archivedData(withRootObject: mDict) as NSData
if let fileAssigend = fileURL {
data.write(to: fileAssigend as URL, atomically: true)
}
}
func read(file: String) -> NSDictionary {
setFileURL(file: file)
var data:NSData?
if let url = fileURL {
data = NSData(contentsOf: url as URL)
if let result = data {
return NSKeyedUnarchiver.unarchiveObject(with: result as Data) as! NSDictionary
}
}
let dict = NSDictionary()
return dict
}
}
并与它一起使用
写:
let userDataManager = UserDataManager()
userDataManager.write(file: "userDataDict", mDict: responseObject)
阅读:
let userDataManager = UserDataManager()
let userDataDict = userDataManager.read(file: "userDataDict")
关于iOS - 在 swift 3 中打印和存储字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43143820/