Alexey K
Alexey K

Reputation: 6723

setObject equivalent in Swift

I have obj-c code

[dictionary setObject:[[notification object] objectForKey:@"key"] forKey:@"anotherKey"];

how can I translate this to swift ? Notification is NSNotification object

I tried

dictionary.setValue(notification.valueForKey("key"), forKey: "anotherKey") 

but app crashes with error (sorry for image, paste doesn't work)

enter image description here

Upvotes: 3

Views: 2060

Answers (4)

vadian
vadian

Reputation: 285082

The pure Swift equivalent is

dictionary["anotherKey"] = notification.object?["key"]

If notification.object or the key key does not exist no object will be assigned.

Note:

Never use valueForKey / setValue:forKey: unless you have a distinct idea why you are using KVC.

Upvotes: 5

Purushothaman
Purushothaman

Reputation: 358

dictionary["anotherKey"] = (notification.object!["key"] as! String)

Upvotes: 0

Erik Terwan
Erik Terwan

Reputation: 2780

How about making your dict a var (not let) and doing this:

dictionary["anotherKey"] = [[notification object] objectForKey:@"key"]

Upvotes: 1

Sarabjit Singh
Sarabjit Singh

Reputation: 1824

Try this may be it helps you:

dictionary .setValue(notification.object["key"], forKey: "anotherKey")

Upvotes: 1

Related Questions