[英]Swift: Shorthand way of moving JSON strings to an array
我有一个项目,我必须从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]
}
}
这在工作时就起作用了,但它让我发疯了,因为它极大地忽视了DRY原理,并且如果需要的话,通过冗长的打字来更改它会花费很多时间。 我只是想知道什么是重构此方法的好方法,因为我已经用尽了所有想法。 提前致谢。
只需使用一个循环:
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)
}
}
}
如果要收集所有 (不是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
您可以对以下任务使用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.