【问题标题】:Swift - What if the value in a key-value dictionary contained another key-value pair inside it?Swift - 如果键值字典中的值包含另一个键值对怎么办?
【发布时间】:2018-03-07 22:34:56
【问题描述】:

根据这个post,在key已知的情况下获取字典中对应的值:

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

【问题讨论】:

  • 所有的分号是怎么回事?这是 Swift,而不是 Objective-C。它们是可选的,仅当您将多个语句放在一行时才应使用(并且不要将多个语句放在一行中。)
  • @DuncanC 这只是 Java 编码的遗留习惯。
  • 好吧,我来自C、C++和Objective-C,它们也都是分号。 Swift 程序员不使用分号。学会不要使用它们。

标签: swift dictionary key


【解决方案1】:

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

 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
   }


} 

希望这会有所帮助

【讨论】:

  • 1. player 将是可选的。 2.sumInt。你不能为Double 退回它。 3. 如果没有找到playerName,你应该返回nil
  • 我会将sum 的声明移到if 中,否则看起来不错。
  • 我也改了,希望能回答你的问题
【解决方案2】:

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

这是一个sn-p:

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"))

【讨论】:

  • 你应该返回 nil is playerScores is nil.
【解决方案3】:

你可以试试

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
   }

【讨论】:

  • 这实际上是我的第一次尝试,它给我带来了同样的错误(可选类型的值 '[String : Int]?' 没有展开)
  • 不要强制转换字典访问。给定的 playerName 可能没有条目。
  • 为什么要迭代密钥?只需迭代值。
  • 我会删除分号。如果没有匹配的玩家,我会返回nil。但这只是我。 :)
  • 你能从非可选函数返回 nil 吗?
猜你喜欢
  • 1970-01-01
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
  • 2017-08-05
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多