Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert value of type '[NSObject : AnyObject]' to expected argument type '[String : AnyObject]'

Tags:

swift

xcode7

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.

like image 947
Lifu Lin Avatar asked Sep 21 '15 09:09

Lifu Lin


2 Answers

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])
like image 102
Shamsudheen TK Avatar answered Oct 25 '22 22:10

Shamsudheen TK


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

like image 40
inokey Avatar answered Oct 25 '22 20:10

inokey