【发布时间】: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