[英]Trying to saveArray, got error - Cannot convert value of type '[Data]' to expected argument type '[Dictionary<String, AnyObject>]'
I'm trying to save array added from tableview using this function: 我正在尝试使用此功能保存从tableview添加的数组:
class func saveArray(_ value: [Dictionary<String, AnyObject>], key: String) {
let data = NSKeyedArchiver.archivedData(withRootObject: value)
UserDefaults.standard.set(data, forKey: key)
}
Below is the function where I want to save the array: 下面是我要保存数组的函数:
func addItemCat(items: [Data]) {
print("ITEM: ", items)
dataSource.myListTableViewController.myListArr = items
self.myListTV.isHidden = false
UserDefaultsHelper.saveArray(items, key: Constants.myList.myList)
}
However, I got this error: Cannot convert value of type '[Data]' to expected argument type '[Dictionary String, AnyObject ]' 但是,我收到此错误:无法将类型[Data]的值转换为预期的参数类型'[Dictionary String,AnyObject]'
Below is my Data model: data model screencap 以下是我的数据模型: 数据模型屏幕截图
I'm new to Swift and I hope someone can explain what is the problem. 我是Swift的新手,我希望有人可以解释问题所在。
Problem is with data types, saveArray
function expects value parameter of type array of dictionary [Dictionary<String, AnyObject>]
, but you are passing array of data model objects which is a type-mismatch error. 问题在于数据类型,
saveArray
函数需要字典[Dictionary<String, AnyObject>]
的类型数组的value参数,但是您正在传递数据模型对象的数组,这是类型不匹配的错误。
To solve this: 要解决这个问题:
First, You should not use pre-defined keywords for creating your custom object. 首先,您不应使用预定义的关键字来创建您的自定义对象。 Use
DataObject
instead: 改用
DataObject
:
struct DataObject {
}
Now change your saveArray
function as: 现在将您的
saveArray
函数更改为:
class func saveArray(_ value: [DataObject], key: String) {
let data = NSKeyedArchiver.archivedData(withRootObject: value)
UserDefaults.standard.set(data, forKey: key)
}
and addItemCat
, function as: 和
addItemCat
,功能如下:
func addItemCat(items: [DataObject]) {
print("ITEM: ", items)
dataSource.myListTableViewController.myListArr = items
self.myListTV.isHidden = false
UserDefaultsHelper.saveArray(items, key: Constants.myList.myList)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.