Pintu Rajput Pintu Rajput - 3 years ago 137
Swift Question

How to update key of dictionary in Swift 3

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


I want to update
watcher_following
key with
true/false
but it throws an exception.


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

Answer Source

Do not use NSMutable... collection types in Swift

  • Declare userFollowingArray as Swift Array

    var userFollowingArray = [[String:Any]]()
    
  • Get the Dictionary as variable

    var dict = userFollowingArray[indexPath.row]
    
  • Check the value

    if dict["watcher_following"] as! Bool == false {
    
  • Update it if necessary and assign the dictionary back to the array.

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

    The last step is necessary due to value semantics

It's much more convenient to use a custom struct or class rather than a dicionary.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download