我正在尝试使用 NSJSONSerialization 将 swift 字典(以字符串作为键,将结构作为值)转换为 json 数据。但是我收到了这个错误:
Cannot invoke 'dataWithJSONObject' with an argument list of type'([String : Vik.Version], options: NSJSONWritingOptions, error: nil)
有什么我想念的吗?任何帮助将不胜感激。
谢谢
以下是我的代码。
final class Vik: NSObject {
private struct Version {
private var name: String
private var filesToAdd = [String]()
private var filesToRemove = [String]()
init(name: String, filesToAdd: [String]?, filesToRemove: [String]?) {
self.name = name
if let filesToAdd = filesToAdd {
self.filesToAdd = filesToAdd
}
if let filesToRemove = filesToRemove {
self.filesToRemove = filesToRemove
}
}
}
......
......
......
private var changeLogDict = [String : Version]()
private func addToDirectory() {
.......
.......
let jsonData = NSJSONSerialization.dataWithJSONObject(self.changeLogDict, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
.......
.......
}
}
最佳答案
我想通了。 NSJSONSerialization.dataWithJSON 方法采用“AnyObject”数据类型。 Swift 字典是一个结构而不是一个对象,因此它会提示。以下行编译正常
let jsonData = NSJSONSerialization.dataWithJSONObject(self.changeLogDict as NSDictionary, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
关于swift - 包含结构作为值的 Swift 字典中的 NSJSONSerialization json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30608571/