Search code examples
jsonswifttypescastinganyobject

Cannot convert value of type 'AnyObject?' to expected argument type '[AnyObject]!


I'm using the swift lib "Sync" from Hyperoslo to convert a JSON user to a Core Data object.

let user = JSON.valueForKey("user")
Sync.changes(user , inEntityNamed: "User", dataStack: DataManager.manager, completion: { (response ) -> Void in
    print("USER \(response)")
})

but when a set the first parameter of this method with my JSON object, I have the pre-compiler error:

Cannot convert value of type 'AnyObject?' to expected argument type '[AnyObject]!'

If a replace my first line by...

let user = JSON.valueForKey("user") as! [AnyObject] 

...the app crash with this error:

Could not cast value of type '__NSCFDictionary' (0x3884d7c8) to 'NSArray' (0x3884d548).

How to deal with this?

SOLVED thanks to the explanations from @Eric.D

let user = [JSON.valueForKey("user")!]

Solution

  • The first parameter for changes() should be an implicitly unwrapped array of AnyObject as specified here:

    https://github.com/hyperoslo/Sync#swift

    but your object user is an optional AnyObject.

    Solution: safely unwrap user then put it inside a [AnyObject] array before using it in changes().