gpt4 book ai didi

swift - 快速限制字典的大小

转载 作者:行者123 更新时间:2023-11-28 14:09:42 24 4
gpt4 key购买 nike

我有这样一本字典:

static var answer = [String: String]()

如何将项目数量限制为特定数量?

最佳答案

这是一个简单的方法:

var answer = [String: String]()
let limit = 3

func addToDictionary(key: String, value: String) {
let keys = answer.keys
if keys.count < limit || keys.contains(key) {
answer[key] = value
}
}

addToDictionary(key: "uno", value: "one")
addToDictionary(key: "dos", value: "two")
addToDictionary(key: "tres", value: "three")
addToDictionary(key: "quatro", value: "four")
addToDictionary(key: "tres", value: "trois")

print(answer) //["uno": "one", "tres": "trois", "dos": "two"]

这不会阻止通过 answer["cinco"] = "five" 直接添加到字典中。正确的方法是创建一个具有 limit 属性的结构。这是一个示例实现:

struct LimitedDictionary<T: Hashable, U> {
private let limit: UInt
private var dictionary = [T: U]()

init(limit: UInt) {
self.limit = limit
}

subscript(key: T) -> U? {
get {
return dictionary[key]
}
set {
let keys = dictionary.keys
if keys.count < limit || keys.contains(key) {
dictionary[key] = newValue
}
}
}

func getDictionary() -> [T: U] {
return dictionary
}
}

用法

var dict = LimitedDictionary<String, String>(limit: 3)

dict["uno"] = "one"
dict["dos"] = "two"
dict["tres"] = "three"
dict["quatro"] = "four"
dict["tres"] = "trois"

dict["uno"] //"one"
dict.getDictionary() //["dos": "two", "tres": "trois", "uno": "one"]

关于swift - 快速限制字典的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52691641/

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