如何通过字典传递功能?

时间:2016-02-27 18:44:46

标签: swift2

我试图在Swift2中使用函数式编程概念(所以请不要推荐使用类)。我是Swift和静态打字的初学者。

因此,如果不使用类,我如何将字典本身的字典值传递给函数。例如:

func recordStrokes(strokes: Int, forHole:Int, var scoreCard: Dictionary<Int, Int>) -> [Int:Int]{
    scoreCard[forHole] = strokes
    return scoreCard
}


var player1 = [ "name": "Lionel","score": [:]]

player1["score"] = recordStrokes(3, forHole: 1, scoreCard: player1["score"])

我想要完成的是保持高尔夫球比赛的总和。当我使用上面的代码时,我得到了错误:

  

错误:无法下标类型的值&#39; [String:NSObject]&#39;索引类型&#39;字符串&#39;

  

注意:&#39;下标&#39;的重载存在这些部分匹配的参数列表:(DictionaryIndex),(Key),(Range),(Self.Index)   recordStrokes(3,forHole:1,scoreCard:player1 [&#34;得分&#34;])

非常感谢任何和所有帮助。

1 个答案:

答案 0 :(得分:1)

传递给你的函数的scoreCard类型不正确......

func recordStrokes(strokes: Int, forHole:Int, var scoreCard: Dictionary<Int, Int>) -> [Int:Int]{
    scoreCard[forHole] = strokes
    return scoreCard
}


var player1:[String:Any] = [ "name": "Lionel","score": [Int:Int]()]

let ps = player1["score"] as! [Int:Int]
player1["score"] = recordStrokes(3, forHole: 1, scoreCard: ps)

print(player1) // ["score": [1: 3], "name": "Lionel"]
顺便说一句,如果在代码中使用类或结构,它与函数式范例没有任何关系。你的代码(因为这个代码片段)不是用函数式编写的......