gpt4 book ai didi

swift - 不能使用字符串类型的索引下标 NSDictionary 类型的值

转载 作者:IT王子 更新时间:2023-10-29 05:18:50 27 4
gpt4 key购买 nike

    var url: NSURL = NSURL(string: urlPath)!

var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
request.HTTPMethod = "GET"

var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error:nil)!

var err: NSError
println(dataVal)


//var jsonResult : NSDictionary?
var jsonResult = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary

println("Synchronous \(jsonResult)")
jsonResult["records"]

这是错误发生的地方,我只想从我的 jsonResult 中获取一个值,它在控制台上正确打印。

最佳答案

您正在将 jsonResult 类型转换为 NSDictionary,而不是使用 [String:AnyObject]

如果你正在使用 NSDictionary,你应该使用 valueForKey(key) 或者 objectForKey(key) 方法 NSDictionary 获取 key 的值。

    var url: NSURL = NSURL(string: urlPath)!
var err: NSError?

var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
request.HTTPMethod = "GET"

var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error:nil)!

var err: NSError
println(dataVal)


//var jsonResult : NSDictionary?
var jsonResult:AnyObject? = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableLeaves, error: &err)

println("Synchronous \(jsonResult)")
if let result = jsonResult as? [String: AnyObject] {
if let oneValue = result["records"] as? String { //Here i am considering value for jsonResult["records"] as String, if it other than String, please change it.
println(oneValue)
}
}

关于swift - 不能使用字符串类型的索引下标 NSDictionary 类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30393205/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com