3

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")!]
Damien Romito
  • 9,801
  • 13
  • 66
  • 84
  • 1
    user is a Dictionary not an Array so if you force cast it to something it isn't then it will bomb. Do if let user = JSON.valueForKey("user") as? Dictionary – Max MacLeod Oct 28 '15 at 15:46

2 Answers2

3

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().

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
1

To start, user is an optional AnyObject. You can never expect that you can use an optional where anything non optional is required. Typically you will use "if let" to check whether the optional is there.

But really, do you want to put an AnyObject in your database? This is asking for trouble. Check first that it has the right type.

gnasher729
  • 51,477
  • 5
  • 75
  • 98