根据这个post ,如果已知键,则获取字典中对应的值:
let val = dict[key]
但是如果字典是这种形式呢(这会被称为字典中的字典吗?):
var myDict : [String:[String:Int]] = [String:[String:Int]]();
在我的代码中:
var scores : [String:[String:Int]] = [player : [sport: point]]();
var player : String = "";
var sport : String = "";
var point : Int = 0;
我有一个函数,它将玩家的名字作为参数传递,并希望获得他所有分数的 Double 总和,即
public func sumPoints(playerName : String) -> Double? {
let val = scores[playerName]
var sum : Double = 0;
for item in val {
// I have trouble how to separate the 'point' from [sport : point] then parse it to Double
// Here, my value is [sport : point] with the key being [playerName] (or 'player'); but I only want to extract the 'point' not 'sport'
// Because if I do the following:
sum += item; // Error: value of optional type '[String : Int]?' not unwrapped
}
return sum;
}
我只想从[player: [sport:point]]
中提取point
。
最佳答案
你可以像这样获取(键,值)并执行你想要的任何操作(键,值)
public func sumPoints(playerName : String) -> Double? {
if let player = scores[playerName] {
var sum = 0.0
for (key, value) in player {
sum += value
}
return sum;
}else {
return nil
}
}
希望这会有所帮助
关于Swift - 如果键值字典中的值包含另一个键值对怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49162346/