简体   繁体   English

如何在Swift中从索引处的Array()获取值?

[英]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] ? 我认为jsonDictNSDictionary还是[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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM