我已经启动了一个 Swift 2 项目,我正试图将我的头脑集中在 do
、guard
和 throws
上。 Stack 上还有其他几个与此相关的问题,但我遇到的问题略有不同。
这是我的代码:
enum JSONParsingError: String, ErrorType {
case URLCreationFailed = "Error: URL creation failed"
case SerializationFailed = "Error: JSON Parsing failed"
case DataDownloadingFailed = "Error: downloading data failed"
case DictionaryError = "Error: dictionary creation from JSON failed."
}
func fetchUserRepositories(urlString: String) throws {
do {
guard let reposURL = NSURL(string: urlString) else { throw JSONParsingError.URLCreationFailed }
guard let jsonData = NSData(contentsOfURL: reposURL) else { throw JSONParsingError.DataDownloadingFailed }
guard let jsonDictionary: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers) as? NSDictionary else { throw JSONParsingError.SerializationFailed }
guard let reposArray = jsonDictionary["repos"] as? NSDictionary else { throw JSONParsingError.DictionaryError }
for repo in reposArray {
repositories.append(TestRepo(json: repo))
}
}
}
无论我如何转换 jsonDictionary["repos"]
,我的 for 循环中总是出现相同的错误:
无法将类型“Element”(又名“(key: AnyObject, value: AnyObject)”)的值转换为预期的参数类型“NSDictionary”
(TestRepo 只是一个使用初始化的简单类一本字典。这不是最理想的方式,我知道)。
我错过了什么?
最佳答案
reposArray
是一个字典,它是(key, value)
对的集合。在您的代码中:
for repo in reposArray {
repositories.append(TestRepo(json: repo))
}
repo
依次绑定(bind)到每个元素。因此,如果 TestRepo
需要一个字典作为参数,它会收到一个元素(一对 (key, value)
),这就是错误的原因。
关于ios - Swift 2 - NSJONSerialization.JSONObjectWithData with guard statement "Cannot convert value of type Element...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32212660/