追加元素形成对多维数组的JSON响应

时间:2015-08-19 13:49:36

标签: arrays swift2 alamofire swifty-json

我正在使用Alamofire和SwiftyJSON。

代码:

var array = Array<Array<String>>()

Alamofire.request(.GET, url, parameters: ["postType": "live"], encoding: ParameterEncoding.URL).responseJSON { (_, _, result) in
        switch result {

            case .Success(let data):

                let json = JSON(data)

                for(_,subJSON):(String, JSON) in json["Info"] {

                    let Tag = subJSON["Tag"].string!
                    let Location = subJSON["Location"].string!

                    array.append(Array(count: 4, repeatedValue: concertTag))

                }

            case .Failure(_, let error):

                print("Request failed with error: \(error)")
        }
    }

我想创建一个多维数组。并在将数组传递给TableView之后为其添加JSON变量。

所以基本上我需要&#34;阵列&#34;就像:

[[Tag1; Location1],[Tag2, Location2], .... ]

我该怎么做?有任何想法吗?

谢谢

1 个答案:

答案 0 :(得分:1)

你只需要替换

array.append(Array(count: 4, repeatedValue: concertTag))

array.append([Tag, Location])

你可以像这样得到数据:

for arr in array {
    print("tag: " + arr[0])
    print("loc: " + arr[1])
}

但我建议采用另一种方法:使用元组。

首先,让我们创建一个类型结果,因为它很方便:

typealias TagAndLocation = (tag: String, location: String)

然后准备一个空的结果数组:

var resultTuples = [TagAndLocation]()

在循环中填充元组数组:

for (_, subJSON) in json {
    let Tag = subJSON["Tag"].string!
    let Location = subJSON["Location"].string!

    let tagloc = (tag: Tag, location: Location)
    resultTuples.append(tagloc)
}

然后您可以通过两种方式访问​​您的数据:

for (tag, loc) in resultTuples {
    print("tag: " + tag)
    print("loc: " + loc)
}

for result in resultTuples {
    print("tag: " + result.tag)
    print("loc: " + result.location)
}

注意:您的变量名称应以小写字母开头。从大写开始通常用于类,类型,协议等。