[英]How to get value from an Array() at index in Swift?
let urlPath: String = "http://binaenaleyh.net/dusor/"
var url: NSURL = NSURL(string: urlPath)
var imgData: NSData = NSData(contentsOfURL: url)
let jsonDict = NSJSONSerialization.JSONObjectWithData(imgData, options: nil, error: &error) as NSDictionary
println(jsonDict["dersler"])
It returns the whole JSON value, but I need the value at a specific index only. 它返回整个JSON值,但是我只需要特定索引处的值即可。
I take it jsonDict
is either an NSDictionary
or a [NSObject:AnyObject]
? 我认为
jsonDict
是NSDictionary
还是[NSObject:AnyObject]
? First off, you shouldn't be using valueForKey()
. 首先,您不应该使用
valueForKey()
。 The appropriate method on NSDictionary
is objectForKey
. NSDictionary
上的适当方法是objectForKey
。 But even better, you can just subscript it. 但更好的是,您可以将其下标。
Of course, the results of the subscript are a value typed as AnyObject
, and you can't just subscript that. 当然,下标的结果是一个键入为
AnyObject
的值,您不能仅对它下标。 You need to cast it to the appropriate type. 您需要将其转换为适当的类型。 If you know the cast will succeed you can just use
as
, otherwise you'll need as?
如果您知道强制转换将成功,则可以使用
as
,否则需要as?
. 。 Assuming the latter, this would look like
假设后者看起来像
if let ary = jsonDict["dersler"] as? [Int] {
let x: Int = ary[0]
println(x)
}
Surely you can just do... 当然可以...
println(jsonDict["dersler"][0])
? ?
This has been asked many times too. 这个问题也被问过很多次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.