我的json文件:
[{
"cardId": "1412015 T",
"firstname": "Abesh",
"lastname": "Shakya",
"designation": "Jr. System Administrator",
"department": "Technology"
},
{
"cardId": "1412015 T",
"firstname": "Rbesh",
"lastname": "Shakya",
"designation": "Jr. System Administrator",
"department": "Admin"
}
]
如何申请循环并添加if条件,以便如果department是techology,则在techname数组中保存firstname和lastname值,否则为adminName数组
答案 0 :(得分:2)
想象一下,您从服务器下载了一些数据。您将使用
将数据转换为字典let arrayOfDictionaries = try! NSJSONSerialization.JSONObjectWithData(
data,
options: .AllowFragments
)
var techNames : [String] = []
var adminNames : [String] = []
然后你可以迭代做
for dictionary in arrayOfDictionaries {
if dictionary["department"] == "Technology" {
// Add name to techNames
techNames.append(completeNameForPerson(dictionary))
} else {
// Do something else
adminNames.append(completeNameForPerson(dictionary))
}
}
func completeNameForPerson(person : [String : String]) -> String {
return "\(person["firstname"]!) \(person["lastname"]!)"
}
这是一个常见问题,请在开设新讨论主题之前进行搜索。