gpt4 book ai didi

arrays - 在 Swift 中轻松访问和修改字典数组

转载 作者:行者123 更新时间:2023-11-28 08:20:10 25 4
gpt4 key购买 nike

我有这样的结构:[String: [String: Double]]()

具体来说,是这样的:var dictionaries = ["GF": ["ET": 4.62, "EO": 21.0],"FD": ["EE": 80.95, "DE": 0.4 ]]

如何轻松访问和修改嵌套词典?

EXAMPLE UPDATED:我想在 FD 处附加 "TT": 6,稍后我想在数组中附加另一个字典。最后我会打印结果。

for (key,value) in dictionaries {

// if array contains FD, add the record to FD
if key.contains("FD") {
dictionaries["FD"]!["TT"] = 6
}
else {
// if array doesn't contain FD, add FD and add the record to it
dictionaries = dictionaries+["FD"]["TT"] = 6 // <-- I know that it's wrong but I want to achieve this result in this case.
}
}

打印结果为:

GF -> ET - 4.62, EO - 21.0
FD -> EE - 80.95, DE - 0.4, TT - 6

任务:我需要像上面的例子一样追加新的字典记录,以简单直接的方式更新现有的记录,轻松地遍历记录以读取值并将它们打印出来。

谁能帮帮我?从那时起就再也没有机会在 Swift 中管理字典。

最佳答案

不清楚你到底需要什么,但这个练习让我很开心,所以我 came up使用此解决方案:我们扩展 Dictionary,以便它在嵌套字典时提供方便的方法。

首先,由于 Swift 的特性,我们必须创建一个虚拟协议(protocol)来“标记”Dictionary¹:

protocol DictionaryProtocol {
associatedtype Key: Hashable
associatedtype Value

subscript(key: Key) -> Value? { get set }
var keys: LazyMapCollection<[Key : Value], Key> { get }
}

extension Dictionary: DictionaryProtocol {}

基本上,只需将以后需要的所有声明从 Dictionary 复制粘贴到 DictionaryProtocol

然后,你就可以愉快地拉伸(stretch)开来了。例如,添加一个双参数下标:

extension Dictionary where Value: DictionaryProtocol {
typealias K1 = Key
typealias K2 = Value.Key
typealias V = Value.Value

subscript(k1: K1, k2: K2) -> V? {
get {
return self[k1]?[k2]
}
set {
if self[k1] == nil {
self.updateValue([K2: V]() as! Value, forKey: k1)
}

self[k1]![k2] = newValue
}
}
}

或者另一种 pretty-print ³:

extension Dictionary where Value: DictionaryProtocol {
func pretty() -> String {
return self.keys.map { k1 in
let row = self[k1]!.keys.map { k2 in
return "\(k2) - \(self[k1]![k2]!)"
}.joined(separator: ", ")

return "\(k1) -> \(row)"
}.joined(separator: "\n")
}
}

你也可以为这个特殊的字典创建一个类型别名:

typealias D2Dictionary<K: Hashable, V> = Dictionary<K, Dictionary<K, V>>

回到你问题中的例子:

var dictionary = D2Dictionary<String, Double>()
dictionary["GF", "ET"] = 4.62
dictionary["GF", "EO"] = 21.0
dictionary["FD", "EE"] = 80.95
dictionary["FD", "DE"] = 0.4
dictionary["FD", "TT"] = 6

print(dictionary.pretty())

// > GF -> ET - 4.62, EO - 21.0
// > FD -> EE - 80.95, DE - 0.4, TT - 6.0

  1. 背景:在扩展条件的类型边界中只能使用协议(protocol)。
  2. 确保类型正确。例如,如果我们写 var keys: [Key] { get },编译器 dies with a seg fault .
  3. 不幸的是,无论出于何种原因,extension Dictionary: CustomStringConvertible where Value: DictionaryProtocol { ... } 都是不允许的。

关于arrays - 在 Swift 中轻松访问和修改字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41560243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com