我有一本这样的字典:
static var answer = [String: String]()
如何将商品数量限制为特定数量?
答案 0 :(得分:1)
这是一种简单的方法:
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"]