Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setObject equivalent in Swift

Tags:

ios

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

like image 239
Alexey K Avatar asked Dec 20 '25 00:12

Alexey K


2 Answers

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.

like image 99
vadian Avatar answered Dec 21 '25 14:12

vadian


Try this may be it helps you:

dictionary .setValue(notification.object["key"], forKey: "anotherKey")
like image 25
Sarabjit Singh Avatar answered Dec 21 '25 14:12

Sarabjit Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!