Swift 中的 setObject 等价物

Ale*_*y K 3 ios swift

我有 obj-c 代码

[dictionary setObject:[[notification object] objectForKey:@"key"] forKey:@"anotherKey"];
Run Code Online (Sandbox Code Playgroud)

我怎么能把它翻译成 swift ?通知是 NSNotification 对象

我试过

dictionary.setValue(notification.valueForKey("key"), forKey: "anotherKey") 
Run Code Online (Sandbox Code Playgroud)

但应用程序因错误而崩溃(抱歉图片,粘贴不起作用)

在此处输入图片说明

vad*_*ian 5

纯 Swift 等价物是

dictionary["anotherKey"] = notification.object?["key"]
Run Code Online (Sandbox Code Playgroud)

如果notification.object或 键key不存在,则不会分配任何对象。

注意

永远不要使用valueForKey/ ,setValue:forKey:除非您对使用 KVC 的原因有清楚的了解。