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.
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])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With