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

时间:2017-07-25 10:53:52

标签: swift dictionary

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>
}

我想用watcher_following更新true/false密钥,但会引发异常。

  

[_ TtGCs26_SwiftDeferredNSDictionarySSP__   _swift_setObject:forKeyedSubscript:]:无法识别的选择器发送到实例

2 个答案:

答案 0 :(得分:1)

不要在Swift

中使用NSMutable...集合类型
  • userFollowingArray声明为Swift数组

    var userFollowingArray = [[String:Any]]()
    
  • 获取Dictionary var iable

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

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

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

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

使用自定义结构或类而不是指南针更加方便。

答案 1 :(得分:0)

为可变类型声明varlet仅用于不可变/常量类型。不需要使用目标c NSMutableDictionary类型。

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