在纯Swift

时间:2016-02-11 11:38:02

标签: json swift recursion

假设有一个嵌套(有效)的JSON结构,如:

{
  "artists": {
    "offset": 0,
    "next": null,
    "href": "https:\/\/api.spotify.com\/v1\/search?query=tania+bowra&offset=0&limit=20&type=artist",
    "limit": 20,
    "previous": null,
    "total": 1,
    "items": [
      {
        "genres": [
        ],
        "images": [
          {
            "url": "https:\/\/i.scdn.co\/image\/f2798ddab0c7b76dc2d270b65c4f67ddef7f6718",
            "width": 640,
            "height": 640
          },
          {
            "url": "https:\/\/i.scdn.co\/image\/b414091165ea0f4172089c2fc67bb35aa37cfc55",
            "width": 300,
            "height": 300
          },
          {
            "url": "https:\/\/i.scdn.co\/image\/8522fc78be4bf4e83fea8e67bb742e7d3dfe21b4",
            "width": 64,
            "height": 64
          }
        ],
        "id": "08td7MxkoHQkXnWAYD8d6Q",
        "external_urls": {
          "spotify": "https:\/\/open.spotify.com\/artist\/08td7MxkoHQkXnWAYD8d6Q"
        },
        "popularity": 2,
        "followers": {
          "total": 25,
          "href": null
        },
        "href": "https:\/\/api.spotify.com\/v1\/artists\/08td7MxkoHQkXnWAYD8d6Q",
        "type": "artist",
        "name": "Tania Bowra",
        "uri": "spotify:artist:08td7MxkoHQkXnWAYD8d6Q"
      }
    ]
  }
}

我想在纯Swift lang(没有Apple Cocoa Foundation依赖项)中遍历此结构,以便递归地访问每个节点到leafs 为了应用定义为

block闭包
closure : (key:String, value:AnyObject, list:[String:AnyObject]) 

其中list参数的行为类似于Accumulator

累加器list中的输出必须与输入json的结构相同:

var json:[String:AnyObject]! = [String:AnyObject]();

例如,我在Swift中编写了一个递归闭包,并传递了acc。在这种情况下,我只是在[String:Int!] Swift.Dictionary

的总和
var closure:( ([String:Int!], acc:[String:AnyObject]) -> [String:Int!])!
closure = { (var x, var l) in
    if (x["value"] >= 10) {
        closure = nil;
        return x;
    } else {
        x["value"]=x["value"]!+1;

        return closure(x, acc:l)
    }
}

var list:[String:AnyObject]! = [String:AnyObject]();
let kv:[String:Int!] = [
    "value" : 0,
];
let value = closure(kv,acc:list)
print(value);

0 个答案:

没有答案