2017-07-25 122 views
0
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/falsewatcher_following关键,但它抛出一个异常。如何斯威夫特3

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

+1

将'let dict'改为'var dict',然后尝试 –

+0

它是在tapped action中吗? –

+2

为什么NSMutableDictionary而不是var中的Swift字典?为什么强制铸造一切?这是斯威夫特,但这看起来更像Objective-C比斯威夫特3 ... – Moritz

回答

1

不要使用NSMutable...集合类型斯威夫特

  • 声明userFollowingArray为雨燕阵列

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

    var dict = userFollowingArray[indexPath.row] 
    
  • 检查值,如果必要

    if dict["watcher_following"] as! Bool == false { 
    
  • 更新和分配字典回阵列。

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

    的最后一步是必要的,因为值语义

它更方便地使用自定义的结构或类,而不是dicionary。

0

声明var为可变类型,let仅用于不可改变/常数类型。不需要使用客观的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> 
}