First you should do is to properly define type of the graph
, because unlike Python
you have to specify types in Swift
in declaration:
var graph: [String: [String: Int]] // Dictionary(hash table) with keys of type String and values of type Dictionary<String, Int>
Then you should initialize graph
with some initial value, because in Swift
you always explicitly initialize non-nullable variables:
graph = [:] // empty dictionary, in Python it's {}
Declaration and initialization can be in one line, so you may just do this:
var graph: [String: [String: Int]] = [:]
Then your code snippet, with little changes:
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
But it would be better if you would define "start"
value at once:
graph["start"] = [
"a": 6,
"b": 2
]
Or even do it for whole graph
:
let graph: [String: [String: Int]] = [
"start": [
"a": 6,
"b": 2
]
]
solved How to implement this Python code in Swift?