我不确定我是否正在使用字典或数据对象或两者都不正确。我试图习惯切换到快速但我有点麻烦。
var dictionaryExample : [String:AnyObject] =
["user":"UserName",
"pass":"password",
"token":"0123456789",
"image":0] // image should be either NSData or empty
let dataExample : NSData = dictionaryExample as NSData
我需要NSDictionary
对NSData
对象进行编码,然后将NSData
对象解码为NSDictionary
。
非常感谢任何帮助,谢谢。
答案 0 :(得分:106)
您可以使用NSKeyedArchiver
和NSKeyedUnarchiver
swift 2.0 +的示例
var dictionaryExample : [String:AnyObject] = ["user":"UserName", "pass":"password", "token":"0123456789", "image":0]
let dataExample : NSData = NSKeyedArchiver.archivedDataWithRootObject(dictionaryExample)
let dictionary:NSDictionary? = NSKeyedUnarchiver.unarchiveObjectWithData(dataExample)! as? NSDictionary
<强> Swift3.0 强>
let dataExample: Data = NSKeyedArchiver.archivedData(withRootObject: dictionaryExample)
let dictionary: Dictionary? = NSKeyedUnarchiver.unarchiveObject(with: dataExample) as! [String : Any]
游乐场的截图
答案 1 :(得分:8)
NSPropertyListSerialization可能是另一种解决方案。
// Swift Dictionary To Data.
var data = try NSPropertyListSerialization.dataWithPropertyList(dictionaryExample, format: NSPropertyListFormat.BinaryFormat_v1_0, options: 0)
// Data to Swift Dictionary
var dicFromData = (try NSPropertyListSerialization.propertyListWithData(data, options: NSPropertyListReadOptions.Immutable, format: nil)) as! Dictionary<String, AnyObject>
答案 2 :(得分:3)
对于Swift 3:
let data = try PropertyListSerialization.data(fromPropertyList: authResponse, format: PropertyListSerialization.PropertyListFormat.binary, options: 0)
答案 3 :(得分:3)
Leo's answer给了我构建时间错误,因为NSData
与Data
不同。函数unarchiveObject(with:)
采用Data
类型的变量,而函数unarchiveTopLevelObjectWithData()
采用NSData
类型的变量。
这是一个有效的 Swift 3 答案:
var names : NSDictionary = ["name":["John Smith"], "age": 35]
let namesData : NSData = NSKeyedArchiver.archivedData(withRootObject: names) as NSData
do{
let backToNames = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(namesData) as! NSDictionary
print(backToNames)
}catch{
print("Unable to successfully convert NSData to NSDictionary")
}
答案 4 :(得分:3)
Swift 5
正如@yuyeqingshan所说,PropertyListSerialization
是一个不错的选择
// Swift Dictionary To Data.
do {
let data = try PropertyListSerialization.data(fromPropertyList: [:], format: PropertyListSerialization.PropertyListFormat.binary, options: 0)
// do sth
} catch{
print(error)
}
// Data to Swift Dictionary
do {
let dicFromData = try PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.ReadOptions.mutableContainers, format: nil)
if let dict = dicFromData as? [String: Any]{
// do sth
}
} catch{
print(error)
}
答案 5 :(得分:-3)
对于Swift 4 -
let dictionaryExample : [String:AnyObject] = ["user":"UserName" as AnyObject, "pass":"password" as AnyObject, "token":"0123456789" as AnyObject, "image":0 as AnyObject]
let dataExample : NSData = NSKeyedArchiver.archivedData(withRootObject: dictionaryExample) as NSData
let dictionary:NSDictionary? = NSKeyedUnarchiver.unarchiveObject(with: dataExample as Data)! as? NSDictionary