[英]Swift: Shorthand way of moving JSON strings to an array
I have a project where I have to take a bunch of Logo URL's and Title's from a JSON object and then I have used Alamofire and SwiftyJSON to extract this information like so: 我有一个项目,我必须从JSON对象中提取一堆徽标URL和标题,然后使用Alamofire和SwiftyJSON提取此信息,如下所示:
Alamofire.request(.POST, postJsonURL, parameters: postParameters, encoding: .JSON).responseJSON {
(request, response, json, error) -> Void in
if (json != nil) {
var jsonObj = JSON(json!)
var title1 = jsonObj[0]["title"].stringValue
var title2 = jsonObj[1]["title"].stringValue
var title3 = jsonObj[2]["title"].stringValue
var title4 = jsonObj[3]["title"].stringValue
var title5 = jsonObj[4]["title"].stringValue
var image1 = jsonObj[0]["logoURL"].stringValue
var image2 = jsonObj[1]["logoURL"].stringValue
var image3 = jsonObj[2]["logoURL"].stringValue
var image4 = jsonObj[3]["logoURL"].stringValue
var image5 = jsonObj[4]["logoURL"].stringValue
self.images = [image1, image2, image3, image4, image5]
self.titles = [title1, title2, title3, title4, title5]
}
}
This works at the minute but it is driving me mad because it's a big disregard to the DRY principle and it would take forever to change it by tedious typing, should I need to. 这在工作时就起作用了,但它让我发疯了,因为它极大地忽视了DRY原理,并且如果需要的话,通过冗长的打字来更改它会花费很多时间。 I was just wondering what's a good way to refactor this as I have ran out of ideas. 我只是想知道什么是重构此方法的好方法,因为我已经用尽了所有想法。 Thanks in advance. 提前致谢。
Just use a loop: 只需使用一个循环:
Alamofire.request(.POST, postJsonURL, parameters: postParameters, encoding: .JSON).responseJSON {
(request, response, json, error) -> Void in
if (json != nil) {
var jsonObj = JSON(json!)
self.images = []
self.titles = []
for (var i=0; i < 5; ++i) {
self.images.append(jsonObj[i]["logoURL"].stringValue)
self.titles.append(jsonObj[i]["title"].stringValue)
}
}
}
If you want to collect all (not 0...4
) elements, just iterate jsonObj
: 如果要收集所有 (不是0...4
)元素,只需迭代jsonObj
:
var jsonObj = JSON(json!)
var images:[String]
var titles:[String]
for (idx, obj) in jsonObj {
titles.append(obj["title"].stringValue)
images.append(obj["logoURL"].stringValue)
}
self.images = images
self.titles = titles
You can use reduce for tasks like this: 您可以对以下任务使用reduce:
var titles = jsonObj.reduce([] as [String]) {
p, n in
var temp = p
temp.append(n["title"]!)
return temp
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.