无法转换'AnyObject'类型的值?到期望的参数类型'[AnyObject]!

时间:2021-04-15 15:21:40

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

我正在使用Hyperoslo的swift lib“Sync”将JSON用户转换为Core Data对象。

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:

但是当使用我的JSON对象设置此方法的第一个参数时,我有预编译错误:

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

无法转换'AnyObject'类型的值?预期的参数类型'[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).

无法将类型'__NSCFDictionary'(0x3884d7c8)的值转换为'NSArray'(0x3884d548)。

How to deal with this?

怎么处理这个?

SOLVED thanks to the explanations from @Eric.D

解决了@ Eric.D的解释

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

2 个解决方案

#1


3  

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

changes()的第一个参数应该是一个隐式解包的AnyObject数组,如下所示:

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

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

but your object user is an optional AnyObject.

但是您的对象用户是可选的AnyObject。

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

解决方案:安全地解包用户然后将其放在[AnyObject]数组中,然后在changes()中使用它。

#2


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.

首先,user是可选的AnyObject。你永远不能指望你可以选择任何非可选的东西。通常,您将使用“if let”来检查是否存在可选项。

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.

但是,你真的想在你的数据库中放一个AnyObject吗?这是在惹麻烦。首先检查它是否具有正确的类型。

#1


3  

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

changes()的第一个参数应该是一个隐式解包的AnyObject数组,如下所示:

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

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

but your object user is an optional AnyObject.

但是您的对象用户是可选的AnyObject。

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

解决方案:安全地解包用户然后将其放在[AnyObject]数组中,然后在changes()中使用它。

#2


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.

首先,user是可选的AnyObject。你永远不能指望你可以选择任何非可选的东西。通常,您将使用“if let”来检查是否存在可选项。

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.

但是,你真的想在你的数据库中放一个AnyObject吗?这是在惹麻烦。首先检查它是否具有正确的类型。