[英]How to implement this Python code in Swift?
如何在哈希表中實現哈希表? 該示例是用 Python 編寫的,我需要用 Swift 編寫它。
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2
首先你應該做的是正確定義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
]
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.