如何在Swift中实现此Python代码?

时间:2019-02-25 12:29:46

标签: python swift dictionary

如何在哈希表中实现哈希表?该示例用Python编写,我需要用Swift编写。

graph["start"] = {} 
graph["start"]["a"] = 6
graph["start"]["b"] = 2

1 个答案:

答案 0 :(得分:1)

首先,您应该做的是正确定义graph的类型,因为与Python不同,您必须在声明的Swift中指定类型:

var graph: [String: [String: Int]] // Dictionary(hash table) with keys of type String and values of type Dictionary<String, Int>

然后,您应该使用某个初始值初始化graph,因为在Swift中,您总是显式初始化非空变量:

graph = [:] // empty dictionary, in Python it's {}

声明和初始化可以在一行中,因此您可以这样做:

var graph: [String: [String: Int]] = [:]

然后您的代码段,只需进行少量更改即可:

graph["start"] = [:]
graph["start"]?["a"] = 6 // ? can be replaced with ! here, because we know for sure "start" exists
graph["start"]?["b"] = 2 // but for simple tutorial purposes, I chose to use ? here

但是最好一次定义"start"值:

graph["start"] = [
    "a": 6,
    "b": 2
]

甚至整个graph都这样做:

let graph: [String: [String: Int]] = [
    "start": [
        "a": 6,
        "b": 2
    ]
]