首先你应该正确定义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]] = [:]
然后你的代码 sn-p,几乎没有变化:
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
]
]