首页 > 解决方案 > 如何在 Swift 中实现这个 Python 代码?

问题描述

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

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

标签: pythonswiftdictionary

解决方案


首先你应该做的是正确定义的类型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
    ]
] 

推荐阅读