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

时间:2018-03-07 22:34:57

标签: 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;

我有一个函数将玩家的名字作为参数传递,并希望获得他所有积分的总和,即。

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;

}

我只想从point中提取[player: [sport:point]]

3 个答案:

答案 0 :(得分:0)

你可以尝试

public func sumPoints(playerName : String) -> Int? {

      var sum : Int = 0

      if let val = scores[playerName]  
      { 

         for value in val.values {
            sum = sum + value          
         }

        return sum
      }

      return nil
   }

答案 1 :(得分:0)

当您尝试获取字典中键的值时,返回值是可选类型(因为键的值可能实际上不存在)。因此,您必须打开可选项以实际使用该值(如果存在)。

这是一个片段:

var scores = ["Jake": ["Soccer": 2]]

public func sumPoints(playerName : String) -> Double? {
    if let playerScores = scores[playerName] {
        var sum : Double = 0
        for score in playerScores {
            sum += Double(score.value)
        }
        return sum
    }
    else {
        return nil
    }
}

print(sumPoints(playerName: "Jake"))

答案 2 :(得分:0)

你得到这样的(键,值)并做你想做的任何操作(键,值)

 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
   }


} 

希望这会有所帮助