Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'String' does not conform to protocol 'NSCopying' error when getting object from NSDictionary

Tags:

ios

swift

I am getting an error when trying to extract an object from a NSDictionary in Swift:

Type 'String' does not conform to protocol 'NSCopying'

I tried to cast the key from String to NSString but I does not solve the issue. Can anyone shed some light? Here is the code:

var excerciseCategoryDictionary = object as NSDictionary

let category = NSEntityDescription.insertNewObjectForEntityForName(NSStringFromClass(ExcerciseCategory.self),
                            inManagedObjectContext: AppDelegate.sharedInstance().managedObjectContext) as ExcerciseCategory

category.name = excerciseCategoryDictionary["name"]

The error occurs on the last line.

enter image description here

like image 844
Rafa de King Avatar asked Jul 13 '14 18:07

Rafa de King


1 Answers

Swift automatically converts NSDictionary as Dictionary<NSObject, AnyObject>. If you know that a value stored in a NSDictionary is a string, then you have to cast to String.

The problem in your case is about the value, not the key, so you just have to cast as follows:

category.name = excerciseCategoryDictionary["name"] as String

or

category.name = excerciseCategoryDictionary["name"] as String?

depending from what's the actual type of the object you are assigning the value

like image 95
Antonio Avatar answered Sep 19 '22 07:09

Antonio