gpt4 book ai didi

ios - 观察添加到 Set 的值 - Swift

转载 作者:搜寻专家 更新时间:2023-11-01 05:56:44 25 4
gpt4 key购买 nike

是否可以观察到添加到 Set 数据结构中的值?

我要实现的目标:

var storedStrings = Set<String>() {
didSet (value) {
// where value is a string that has been added to the Set
}
}

例子:
storedStrings.insert("hello")
didSet 调用,因为已添加新值。

storedString.insert("world")
didSet 再次调用。

storedString.insert("hello")
没有调用 didSet,因为该集合已经包含字符串“hello”

最佳答案

这可能有点贵,但您仍然可以这样做:

var storedStrings = Set<String>() {
didSet {
if storedStrings != oldValue {
print("storedStrings has changed")
let added = storedStrings.subtracting(oldValue)
print("added values: \(added)")
let removed = oldValue.subtracting(storedStrings)
print("removed values: \(removed)")
}
}
}

关于ios - 观察添加到 Set 的值 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39998225/

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