Cannot convert value of type '[NSObject : AnyObject]' to expected argument type '[String : AnyObject]'
Solution 1
Your defautlsToRegister
should be in the following format [String: AnyObject]
Example: The following should work without warning
let defautlsToRegister = ["Test":10]
NSUserDefaults.standardUserDefaults().registerDefaults(defautlsToRegister as [String: AnyObject])
Solution 2
I've noticed a simple thing about this error. I'm not sure if this the case but casting String to NSString
seems to solve the problem for me. I found an explanation that AnyObject
is a type alias to represent instances of any reference type, which is for example: NSString
. But String
is a struct
so it can't be the reference type for AnyObject
.
I see two ways for this:
First:
let keyForMyKey: NSString = NSString(string: "mykey")
let result = dict.objectForKey(keyForMyKey) as? NSMutableArray
Second:
let result = dict.objectForKey(NSString(string: "myKey")) as? NSMUtableArray
More on the problem here: http://drewag.me/posts/swift-s-weird-handling-of-basic-value-types-and-anyobject
Lifu Lin
Updated on July 06, 2022Comments
-
Lifu Lin almost 2 years
Xcode7 and swift, My code:
func loadDefaults() { let settingBundle = NSBundle.mainBundle().pathForResource("Settings", ofType: "bundle") if settingBundle == nil { return } let root = NSDictionary(contentsOfFile: settingBundle!.stringByAppendingString("Root.plist")) let prefrences = root?.objectForKey("PreferenceSpecifiers") as! Array<NSDictionary> let defautlsToRegister = NSMutableDictionary(capacity: root!.count) for prefrence in prefrences { let key = prefrence.objectForKey("Key") as! String! if key != nil { defautlsToRegister.setValue(prefrence.objectForKey("DefaultVale"), forKey: key!) } } NSUserDefaults.standardUserDefaults().registerDefaults(defautlsToRegister as [NSObject: AnyObject]) }
Problem code:
NSUserDefaults.standardUserDefaults().registerDefaults(defautlsToRegister as [NSObject: AnyObject])
building warnings
Cannot convert value of type '[NSObject : AnyObject]' to expected argument type '[String : AnyObject]'
change code:
NSUserDefaults.standardUserDefaults().registerDefaults(defautlsToRegister as [String: AnyObject])
building warnings
'NSMutableDictionary' is not convertible to '[String : AnyObject]'
Please teach me how to do? thanks.
-
Henry Heleine over 8 yearsNailed it. Thanks you so much!
-
Narasimha Nallamsetty almost 8 yearsCan you tell me what is the reason for down voting @down voter?. For me the above code worked.