在不知道键的情况下快速引用字典键和值 [英] Swift Reference to a Dictionary Key and Value Without Knowing Key
问题描述
我有一个定义为
var users = [[String:String]]()
数组中的Dictionary是一个简单的用户名+ yes/no flag [[1stUser:Y],[2ndUser:N],[3rdUser:N]]
The Dictionary inside the array is a simple username + yes/no flag [[1stUser: Y], [2ndUser: N], [3rdUser: N]]
在TableView单元格配置中,我定义了
In my TableView cell configuration, I defined
let userRecord = users[indexPath.row] as NSDictionary
,并且需要 分配cell.textlabel.text =用户名(字典的键)
and need to assign cell.textlabel.text = username (the key of the dictionary)
检查标记(是/否),如果是,则为> cell.accessoryType = UITableViewCellAccessoryType.Checkmark
check flag (Y/N) and if Yes > cell.accessoryType = UITableViewCellAccessoryType.Checkmark
在上面的示例中,我应该仅在1stUser旁边得到一个选中标记.
In the example above, I should get a checkmark next to 1stUser only.
问题是如何在不事先知道字典键('1stUser','2nduser'等)的情况下引用字典键并检查值(是/否)?我见过的所有Swift字典示例都假设我们知道用于检索其值的实际键(例如,users ["1stUser"]对我没有帮助,因为我事先不知道1stUser的值为Y).
The question is how to refer to the dictionary keys ('1stUser', '2nduser' etc.) without knowing them in advance and check values (Y/N)? All the Swift dictionary examples I have seen assume we know the actual key to retrieve its value (e.g users["1stUser"] does not help as I do not know in advance that 1stUser has a Y).
推荐答案
您应该始终知道字典键.如果不这样做,那说明您的数据结构不正确-未知数据应始终在字典的值中,而永远在键的值中.
You should always know your dictionary keys. If you don't, you're structuring your data wrong - unknown data should always be in the value of a dictionary, never the key.
考虑使用带有两个键的字典:用户名"和标志".
Consider instead using a dictionary with two keys: "username" and "flag".
示例代码:
var users = [[String:String]]()
users.append(["username" : "Aaron", "flag" : "yes"])
users.append(["username" : "AspiringDeveloper", "flag" : "yes"])
let userRecord = users[1]
let username = userRecord["username"]!
let flag = userRecord["flag"]!
或者,您可以构建基本类并完全避免使用字典:
Alternatively, you could build a basic class and avoid the dictionaries entirely:
class User {
let username: String
let flag: Bool
init(username:String, flag:Bool) {
self.username = username
self.flag = flag
}
}
var users = [User]()
users.append(User(username: "Aaron", flag: true))
users.append(User(username: "AspiringDeveloper", flag: true))
let userRecord = users[1]
let username = userRecord.username
let flag = userRecord.flag
这篇关于在不知道键的情况下快速引用字典键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!