ios - Swift 2 - NSJONSerialization.JSONObjectWithData with guard statement "Cannot convert value of type Element..."

标签 ios swift swift2

我已经启动了一个 Swift 2 项目,我正试图将我的头脑集中在 doguardthrows 上。 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/

相关文章:

ios - 我想在 Xcode 中使用 telprompt 调用电话号码 "#51234"

swift - 可选类型 'Int?' 的值未展开;您是要使用 '!' 还是 '?' ?

swift - Swift 通用协议(protocol)注入(inject)可能吗?

swift - 无法更改 iOS 11 中 UINavigationBar 的高度

ios - 导航栏标题怎么可能不只在一个特定 View 上居中对齐?

swift - OSReadLittleInt16() 如何转换为 Swift?

ios - 如何在 Swift 中将文本添加到 .csv 数据中?

ios - presentViewController 显示黑页

ios - 我如何检查我是否有特定格式

ios - UINavigationController pushViewController 在中途暂停/卡住