在swift中检查数组中字典的值

时间:2016-03-28 08:26:33

标签: ios swift

我的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数组

1 个答案:

答案 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"]!)"
}

这是一个常见问题,请在开设新讨论主题之前进行搜索。