Swift 访问字典中的值
Swift Accessing Values in Dictionary
我有一个 swift 字典,我正在尝试访问数组中的值。
我制作的词典如下所示:
["results": {
Democrats = {
percent = 67;
raw = 4;
};
Republicans = {
percent = 33;
raw = 2;
};
"total_answers" = 6;
}, "success": 1]
我又做了一本字典来得到这个:
let test = dictionary["results"] as! [String : AnyObject]
["Democrats": {
percent = 67;
raw = 4;
}, "Republicans": {
percent = 33;
raw = 2;
}, "total_answers": 6]
我可以访问如下值:
let testing = test["total_answers"]
我想访问百分比值和原始值,例如:
Democrats = {
percent = 67;
raw = 4;
};
百分比和原始密钥是静态的,但民主党是一个永远不会相同的字符串。
所以这里let democrats:[String : Int] = test["Democrats"] as! [String : Int]
将为您提供新词典,仅包含
Democrats = {
percent = 67;
raw = 4;
};
我不知道你的字典使用的是什么符号,但它不会在 Swift 中编译。
类型为 [String:Any] 的字典可以工作,但操作数据将成为类型转换的噩梦。您应该考虑使用所有值都具有相同类型的常规结构。
例如(对二值元组使用类型别名):
typealias Votes = (percent:Int, raw:Int)
var results = [ "Democrats" : Votes(percent:67, raw:4),
"Repubicans" : Votes(percent:33, raw:2),
"Totals" : Votes(percent:100, raw:6)
]
let democratVotes = results["Democrats"]!.raw
我有一个 swift 字典,我正在尝试访问数组中的值。
我制作的词典如下所示:
["results": {
Democrats = {
percent = 67;
raw = 4;
};
Republicans = {
percent = 33;
raw = 2;
};
"total_answers" = 6;
}, "success": 1]
我又做了一本字典来得到这个:
let test = dictionary["results"] as! [String : AnyObject]
["Democrats": {
percent = 67;
raw = 4;
}, "Republicans": {
percent = 33;
raw = 2;
}, "total_answers": 6]
我可以访问如下值:
let testing = test["total_answers"]
我想访问百分比值和原始值,例如:
Democrats = {
percent = 67;
raw = 4;
};
百分比和原始密钥是静态的,但民主党是一个永远不会相同的字符串。
所以这里let democrats:[String : Int] = test["Democrats"] as! [String : Int]
将为您提供新词典,仅包含
Democrats = {
percent = 67;
raw = 4;
};
我不知道你的字典使用的是什么符号,但它不会在 Swift 中编译。
类型为 [String:Any] 的字典可以工作,但操作数据将成为类型转换的噩梦。您应该考虑使用所有值都具有相同类型的常规结构。
例如(对二值元组使用类型别名):
typealias Votes = (percent:Int, raw:Int)
var results = [ "Democrats" : Votes(percent:67, raw:4),
"Repubicans" : Votes(percent:33, raw:2),
"Totals" : Votes(percent:100, raw:6)
]
let democratVotes = results["Democrats"]!.raw