8
votes

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.

3
Please show example of defautlsToRegister as typeMaxim Shoustin
Does using as! help, as suggested in stackoverflow.com/questions/24099165/…?Tali

3 Answers

5
votes

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])
2
votes

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

0
votes

For me this is worked.

let token = fields["X-AUTH-TOKEN"]! as? [[String : AnyObject]] //{
                // safe to use employees
                self.bindings.setObject(NSString(format: "%@", token!) as String, forKey: "X-AUTH-TOKEN")

Format(NSString method) will work in this scenario.