Swift - 如果键值字典中的值包含另一个键值对怎么办?

标签 swift dictionary key

根据这个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/

相关文章:

ios - NSURLSession didCompleteWithError : how to determine what task it is?

swift - SceneKit – 为什么添加聚光灯会使地板变黑?

python - 如果不修改,dicts 会保留迭代顺序吗?

java - 我怎样才能看到属性变量到底包含什么?

php - 通过外键获取 MySQL

ios - Swift 3 通用参数

ios - UITableViewCell 高度不正确,直到通过滚动重新创建单元格

c++ 从 3 个浮点值生成 unordered_map 的键

python - 使用python在文件中存储字典(哈希)的有效方法?

python - 在字典/ HashMap 中(在Python中)使用对象作为自己的键是否正常?