gpt4 book ai didi

swift - 如何在 Swift 3 中更新字典的键

转载 作者:行者123 更新时间:2023-11-28 06:15:23 25 4
gpt4 key购买 nike

if (userFollowingArray[indexPath.row]["watcher_following"] as! Bool) == false {
let dict : NSMutableDictionary = userFollowingArray[indexPath.row] as! NSMutableDictionary
print(dict)
dict["watcher_following"] = 1
self.userFollowingArray[indexPath.row] = dict as! Dictionary<String, Any>
}

我想用 true/false 更新 watcher_following 键,但它抛出异常。

[_TtGCs26_SwiftDeferredNSDictionarySSP__ _swift_setObject:forKeyedSubscript:]: unrecognized selector sent to instance

最佳答案

不要在 Swift 中使用 NSMutable... 集合类型

  • userFollowingArray 声明为 Swift 数组

    var userFollowingArray = [[String:Any]]()
  • 获取 Dictionary 作为 variable

    var dict = userFollowingArray[indexPath.row]
  • 检查值

    if dict["watcher_following"] as! Bool == false {
  • 如有必要,更新它并将字典分配回数组。

        dict["watcher_following"] = true
    userFollowingArray[indexPath.row] = dict
    }

    由于值语义,最后一步是必要的

使用自定义结构或类比使用字典要方便得多。

关于swift - 如何在 Swift 3 中更新字典的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45301221/

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